AndreiT17 (2) [Avatar] Offline
#1
Hi,

I am new to this forum and I try to remember java programming from while a go (around 12 years...), since I left programming altogether, so I apologize if the question is off topic, or if it does not make sense. I also bought the ebook version of the book, so I am not able to locate the page number.

Anyways, my question is about a statement in section 4.4.6, specifically "Adding multiple elements to an ArrayList", just before/above the Exam Tip:
<blockquote>What happens if you modify the common object references in these lists, myArrList and yourArrList? We have two cases here: in the first one, you reassign the object reference using either of the lists. In this case, the value in the second list will remain unchanged. In the second case, you modify the internals of any of the common list elements—in this case, the change will be reflected in both of the lists.<blockquote>
I understand the first part of this statement, but I don't understand the second part (second case). It looks like even if I change an element in yourArrList (formerly added to the myArrList) this is not reflected in myArrayList (which contains also yourArrList). Please somenone help me understand what do I miss. Below extract of code and output:
Code:
=====
ArrayList<StringBuilder> myArrList = new ArrayList<StringBuilder>();
myArrList.add(new StringBuilder("One"));
myArrList.add(new StringBuilder("Two"));
ArrayList<StringBuilder> yourArrList = new ArrayList<StringBuilder>();
yourArrList.add(new StringBuilder("Three"));
yourArrList.add(new StringBuilder("Four"));
myArrList.addAll(yourArrList);
System.out.println("After adding yourArrList to myArrList");
System.out.println("myArrList:");
for(StringBuilder sb:myArrList){
System.out.println(sb);
}
System.out.println("yourArrList:");
for(StringBuilder sb:yourArrList){
System.out.println(sb);
}

System.out.println("Modify the internal of yourArrList and see what happens with myArrList which contains now yourArrlist");
yourArrList.set(1, new StringBuilder("Ten"));

System.out.println("myArrList:");
for(StringBuilder sb:myArrList){
System.out.println(sb);
}
System.out.println("yourArrList:");
for(StringBuilder sb:yourArrList){
System.out.println(sb);
}

========================================
Output:
======
After adding yourArrList to myArrList
myArrList:
One
Two
Three
Four
yourArrList:
Three
Four
Modify the internal of yourArrList and see what happens with myArrList which contains now yourArrlist
myArrList:
One
Two
Three
Four
yourArrList:
Three
Ten
===========================================

As you can see, myArrList did not change. What do I miss?

Thanks,

Andrei
PS: I sumbmitted this topic as a new topic after originally adding this question to the Errata topic. I fixed this after confirming with Susan Hawkins.