How to clone ArrayList and also clone its contents?

后端 未结 21 1929
小鲜肉
小鲜肉 2020-11-21 06:42

How can I clone an ArrayList and also clone its items in Java?

For example I have:

ArrayList dogs = getDogs();
ArrayList

        
21条回答
  •  鱼传尺愫
    2020-11-21 07:09

    I have found a way, you can use json to serialize/unserialize the list. The serialized list holds no reference to the original object when unserialized.

    Using gson:

    List originalList = new ArrayList<>(); // add some items later
    String listAsJson = gson.toJson(originalList);
    List newList = new Gson().fromJson(listAsJson, new TypeToken>() {}.getType());
    

    You can do that using jackson and any other json library too.

提交回复
热议问题