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

How does ArrayList.clone() method work in Java?

我对数组列表中的克隆概念感到困惑。 例如:

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

输出:-

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);

输出:-

[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}]]

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

谁能解释一下?


根据 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 

cloneArrayList 上不执行 深度复制 / 深度克隆,实际上它执行 浅层 一个,意味着它不复制它包含的东西,它只是复制对那些元素的引用。
您仍然只有 一个 绿色、蓝色和黄色气球。您有一个引用四个气球的列表和一个引用三个气球的列表,这些列表在它们包含的元素数量方面彼此独立。但他们目前指向 的实际气球是共享的。