I am running this code:
public class testttt {
public static void main(String[] args){
ArrayList<StringBuffer> listOne = new ArrayList <StringBuffer>();
listOne.add(new StringBuffer("One"));
listOne.add(new StringBuffer("Two"));
listOne.add(new StringBuffer("Three"));
ArrayList <StringBuffer> listTwo = new ArrayList <StringBuffer>(listOne);
listOne.add(new StringBuffer("Four"));
for (StringBuffer str : listTwo) {
str.append("2");
}
System.out.println("List One: " + listOne);
System.out.println("List Two: " + listTwo);
}
}
I thought by having the "new ArrayList" declaration when initializing listTwo I would have created a distinct array that would be independent from listOne. However, the output is:
List One: [One2, Two2, Three2, Four]
List Two: [One2, Two2, Three2]
I have a suspicion that the listTwo initialization only copied over the references from listOne, but I thought it would have been handled by the "new ArrayList" section.
Any explanation would be greatly appreciated!