我对Array列表中的克隆概念感到困惑。例如:
Balloon green = new Balloon("Green",new Address("greenState", "greencity"));
Balloon green2 = (Balloon)green.clone();
green.setColor("NewGreen");
System.out.println(green);
System.out.println(green2);//color not affected in copy as color is of String type.
//Immutable objects are not shallow copied.
green.getAddress().state="helloState";
System.out.println(green);
System.out.println(green2);//Address does get affected
Output:-
Balloon[color = NewGreen Address = Address {state = greenState, city = greencity}]
Balloon[color = Green Address = Address {state = greenState, city = greencity}]
Balloon[color = NewGreen Address = Address {state = helloState, city = greencity}]
Balloon[color = Green Address = Address {state = helloState, city = greencity}]
所以我很清楚。但是现在让我们获取数组列表。
Balloon red = new Balloon("Red",new Address("redState", "redCity"));
Balloon blue = new Balloon("Blue",new Address("blueState", "blueCity"));
Balloon yellow = new Balloon("yellow",new Address("yellowState", "yellowCity"));
ArrayList<Balloon> list = new ArrayList<>();
list.add(red);
list.add(blue);
list.add(yellow);
ArrayList<Balloon> listCopy = (ArrayList<Balloon>)list.clone();
Balloon green = new Balloon("Green",new Address("greenState", "greencity"));
list.get(1).setColor("color");
list.add(green);
Output:-
[Balloon[color = Red Address = Address {state = redState, city = redCity}], Balloon[color = color Address = Address {state = blueState, city = blueCity}], Balloon[color = yellow Address = Address {state = yellowState, city = yellowCity}], Balloon[color = Green Address = Address {state = greenState, city = greencity}]]
[Balloon[color = Red Address = Address {state = redState, city = redCity}], Balloon[color = color Address = Address {state = blueState, city = blueCity}], Balloon[color = yellow Address = Address {state = yellowState, city = yellowCity}]]
因此,在上面的输出中,更改列表中气球的颜色也会影响副本。但是添加新元素不会反映在副本中。
有人可以解释吗?谢谢!
clone
上的ArrayList
]不会执行深层复制,这意味着它不会复制其包含的内容,而只是复制对这些元素的引用。您仍然分别只有one个绿色,蓝色和黄色的气球。您有一个引用四个气球的列表,一个引用三个气球的列表,这些列表在它们包含多少元素方面彼此独立。但是他们当前指向to的实际气球是共享的。