Vote count:
0
In the code below if an ArrayList points to another ArrayList and if I changed the latter then the first ArrayList will change too, but the story is different for Obejct of type Integer!
Integer a= new Integer(10)
Integer b = a;
a = 20; // but b still remains 10
Why in the code below aList changes but not i?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyClass {
Integer i = null;
List<Integer> aList=new ArrayList<>();
public MyClass(Integer data){
this.i = data;
};
public MyClass(List<Integer> alist){
this.aList = alist;
};
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,3));
MyClass c1 = new MyClass(intList);
// after this line the c1.aList points to intList
// so if I change intList, the c1.aList will change too
System.out.println(Arrays.toString(c1.aList.toArray())); //[1, 2, 3]
intList.remove(0);
System.out.println(Arrays.toString(c1.aList.toArray()));
//[2, 3] (1 is removed from c1.aList too
// but different story for object of type Integer
Integer k = new Integer(10);
MyClass c2 = new MyClass(k);
k = 20;
System.out.println(c2.i);
// why still prints 10! not 20? after all c2.i used to point to k!
}
}
asked 28 secs ago
Why different behavious when referencing to an ArrayList Object than to an Integer Object in Java?
Aucun commentaire:
Enregistrer un commentaire