ArrayList.clone() 方法如何在 Java 中工作?

ros*_*ose 3 java clone list arraylist cloning

我对 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
Run Code Online (Sandbox Code Playgroud)

输出:-

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);
System.out.println(list);
System.out.println(listCopy);
Run Code Online (Sandbox Code Playgroud)

输出:-

[气球[颜色=红色地址=地址{州=红色州,城市=红色城市}],气球[颜色=颜色地址=地址{州=蓝色州,城市=蓝色城市}],气球[颜色=黄色地址=地址{州= YellowState, city = yellowCity}], Balloon[color = Green Address = Address {state = greenState, city = greencity}]],

[Balloon[color = Red Address = Address {state = redState, city = redCity}], Balloon[颜色 = 颜色地址 = 地址 {state = blueState, city = blueCity}], Balloon[color = Yellow 地址 = 地址 {state = YellowState, city = YellowCity}]]

因此,在上面的输出中,更改列表中气球的颜色也会影响副本。但是添加新元素不会反映在副本中。

有人可以解释一下吗?


根据 luk2302 的回答,以下可视化解释了正在发生的事情:

    list   object  listCopy
     |___  red   ___|
     |___  blue  ___|
     |___ yellow ___|


     list.add(green);
    list  object  listCopy
     |___  red   ___|
     |___  blue  ___|
     |___ yellow ___|
     |___ green 


     list.remove(blue);
    list  object  listCopy
     |___  red   ___|
           blue  ___|
     |___ yellow ___|
     |___ green 
Run Code Online (Sandbox Code Playgroud)

luk*_*302 7

clone在 aArrayList上不执行深复制/深克隆,实际上它执行复制,这意味着它不复制它包含的内容,它只是复制对这些元素的引用。
你仍然只有一个绿色、蓝色和黄色的气球。您有一个引用四个气球的列表和一个引用三个的列表,这些列表在它们包含的元素数量方面相互独立。但他们现在是指向实际的气球共享。