Java: recommended solution for deep cloning/copying an instance

后端 未结 9 2263
半阙折子戏
半阙折子戏 2020-11-22 01:28

I\'m wondering if there is a recommended way of doing deep clone/copy of instance in java.

I have 3 solutions in mind, but I can have miss some, and I\'d like to ha

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 02:00

    Joshua Bloch's book has a whole chapter entitled "Item 10: Override Clone Judiciously" in which he goes into why overriding clone for the most part is a bad idea because the Java spec for it creates many problems.

    He provides a few alternatives:

    • Use a factory pattern in place of a constructor:

           public static Yum newInstance(Yum yum);
      
    • Use a copy constructor:

           public Yum(Yum yum);
      

    All of the collection classes in Java support the copy constructor (e.g. new ArrayList(l);)

提交回复
热议问题