Reputation: 744
I am preparing myself to the Java certification and confused with object references in this case. In this piece of code I can't understand why ArrayList's and arrays's elements aren't affected when we assign a new object to them?
ArrayList<StringBuilder> myArrList = new ArrayList<StringBuilder>();
StringBuilder sb1 = new StringBuilder("Jan");
StringBuilder sb2 = new StringBuilder("Feb");
myArrList.add(sb1);
myArrList.add(sb2);
StringBuilder[] array = myArrList.toArray(new StringBuilder[2]);
for(StringBuilder val : array) {
System.out.println(val);
}
StringBuilder sb3 = new StringBuilder("NNN");
sb2 = sb3;
for(StringBuilder val : array) {
System.out.println(val);
}
for(StringBuilder val : myArrList) {
System.out.println(val);
}
Output:
Jan
Feb
Jan
Feb
Jan
Feb
I will be grateful if you could provide simple explanation. Thank you.
Upvotes: 0
Views: 68
Reputation: 691655
References are pointers. Assigning a new value to a variable consists in making this pointer point to another object. So, at the beginning, you have an array with two elements:
array[0] ---> Jan <--- sb1
array[1] ---> Feb <--- sb2
Then you create another StringBuilder, referenced by sb3:
array[0] ---> Jan <--- sb1
array[1] ---> Feb <--- sb2
sb3 --------> NNN
Then you say that the sb2 variable should reference the same object as the sb3 variable:
array[0] ---> Jan <--- sb1
array[1] ---> Feb
sb3 --------> NNN <--- sb2
As you're seeing, array[0] and array[1] still reference the same objects Jan and Feb.
Upvotes: 4