# LeetCode刷题时引发的思考：Java中ArrayList存放的是值还是引用？

## 正文

#### 39. 组合总和

`candidates` 中的数字可以无限制重复被选取。

``````class Solution {

private List<List<Integer>> result = new ArrayList();
private ArrayList<Integer> solution = new ArrayList<>();

public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtracking(candidates,target,0);
return result;
}

public  void backtracking(int[] candidates, int residual, int start) {
if (residual < 0) {
return;
}

if (residual == 0) {
return;
}
for(int i = start;i<candidates.length;i++) {
backtracking(candidates,residual-candidates[i],i);
solution.remove(solution.size()-1);
}
}

}
``````

``````
……
if (residual == 0) {
System.out.println(solution.toString());    //打印solution
return;
}
……

``````

``````
……
if (residual == 0) {
System.out.println("----------");
for (List<Integer> integers : result) {
System.out.println(integers.toString());    //打印List中的内容
}
System.out.println("==========");
return;
}
……

``````

``````public class ArrayListTest {

static class User {
private String name;
private int age;

public User(String name , int age) {
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
int testInt = 10;
testInt = 20;
System.out.println(integerArrayList.toString());

ArrayList<Double> doubleArrayList = new ArrayList<>();
double testDouble = 100.0;
testDouble = 200.0;
System.out.println(doubleArrayList.toString());

ArrayList<User> userArrayList = new ArrayList<>();
User testUser = new User("张三",20);
testUser.age = 22;
for (User user : userArrayList) {
System.out.println(user.toString());
}
}
``````

``````    ……
public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
int testInt = 10;
testInt = 20;
for (Integer integer : integerArrayList) {
System.out.println(integer + " : "+ System.identityHashCode(integer));
}
System.out.println();

ArrayList<Double> doubleArrayList = new ArrayList<>();
double testDouble = 100.0;
testDouble = 200.0;
for (Double aDouble : doubleArrayList) {
}

ArrayList<User> userArrayList = new ArrayList<>();
User testUser = new User("张三",20);
System.out.println("\nUser修改前：");
System.out.println(testUser.toString());
System.out.println(System.identityHashCode(testUser));
testUser.age = 22;
System.out.println("User修改后：");
System.out.println(testUser.toString());
System.out.println(System.identityHashCode(testUser));
System.out.println("\n遍历ArrayList<User>：");
for (User user : userArrayList) {
System.out.println(user.toString());
System.out.println(System.identityHashCode(user));
}

}
……
``````

## 结论

``````
……
if (residual == 0) {