很多博客中已经说得很清楚:
值传递只是值操作,对原来的数据没有影响,操作的对象一般是基本数据类型
引用传递则是对原来数据的真实操作,操作对象一般是类,接口,数组这种很常见的包装类型。
从一个题来看吧,leetcode上面的电话号码组合17题,在函数中加了可以看到数组变化的输出,可以看到,这种数组类型,在递归函数中确实是一直在变化的,在for循环中,上个循环的递归数组结果被带到了本次循环的递归结果中
/**
* @param args
* 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> resList = letterCombinations("23");
for (int i = 0; i < resList.size(); i++) {
System.out.println(resList.get(i));
}
}
public static boolean isDigit(String digits) {
for (int i = 0; i < digits.length(); i++) {
if (digits.charAt(i) < '0' || digits.charAt(i) > '9')
return false;
}
return true;
}
public static List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<String>();
if (digits == null || digits.length() < 1) {
return res;
}
if (!isDigit(digits))
return res;
HashMap<Character, String> hm = new HashMap<Character, String>();
hm.put('0', "");
hm.put('1', "");
hm.put('2', "abc");
hm.put('3', "def");
hm.put('4', "ghi");
hm.put('5', "jkl");
hm.put('6', "mno");
hm.put('7', "pqrs");
hm.put('8', "tuv");
hm.put('9', "wxyz");
char[] ch = new char[digits.length()];
getResult(res, digits, ch, 0, hm);
return res;
}
public static void getResult(List<String> res, String digits,
char[] ch, int curnum, HashMap<Character, String> hm) {
if (curnum == digits.length()) {
res.add(new String(ch));
return;
}
// 取出当前的字母段
char curtelNum = digits.charAt(curnum);
String curcharsString = hm.get(curtelNum);
if (curcharsString.length() != 0) {
for (int i = 0; i < curcharsString.length(); i++) {
System.out.println("===========");
System.out.println("before="+ch[curnum]);
ch[curnum]= curcharsString.charAt(i);
System.out.println("after="+ch[curnum]);
System.out.println("===========");
getResult(res, digits, ch, curnum + 1, hm);
}
} else {
getResult(res, digits, ch, curnum + 1, hm);
}
}
截图截了一部分,可以看到,数组元素在被赋值之前就已经被修改过了,这是上次循环的结果。