I tried to run a for-loop and update a double value in a list , and I found that I failed. I search on the web and I know that when getting double value by List#get(i) method is simply get a copy of the value, such that will not update a value in a list, just like the code below.
List<Double> list1 = new ArrayList<Double>();
list1.add(10.0);
for(int i = 0; i < list1.size() ; i++){
Double value = list1.get(i);
value = value/100;
System.out.println(list1.get(i));
}
//Result 10.0
the only way is use the List#set(i, value) method.
Now I add a Test class
class Test{
Double value;
public Test(Double value){
this.value = value;
}
}
and do the similar thing with Test class
List<Test> list2 = new ArrayList<Test>();
Test test = new Test(10.0);
list2.add(test1);
for(int i = 0; i < list2.size() ; i++){
Test test = list2.get(i);
test.value = test.value / 100;
System.out.println(test.value);
}
//Result 0.1
My question is : Why the value in a list will update. Isn't the test object in a for loop still a copy of the original one ? Is it because of primitive data type or reference difference?
Isn't the test object in a for loop still a copy of the original one?- No, what's being returned bylist2.get(i)in this case is a reference to the originalTestobject.