clone(): ArrayList.clone() I thought does a shallow copy

后端 未结 6 1817
别那么骄傲
别那么骄傲 2020-11-29 05:59
ArrayList a=new ArrayList();
a.add(5);
ArrayList b=(ArrayList)a.clone();
a.add(6);
System.out.println(b.t         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 06:23

    If it was like you thought, then the clone method would be completely useless, because in that case, the following lines would be equivalent:

    ArrayList b = (ArrayList)a.clone();
    ArrayList b = a;
    

    Cloning is - like in real world scenarios - a process of creating two entities with exactly the same properties (at the time of the cloning operation).

    And as Bozho mentioned - avoid the Java clone() concept. Even it's author mentioned, that it is broken.

    This question and it's answers are quite valuable and provide a link to Josh Blochs own comments on his piece of work ;-)

提交回复
热议问题