How do I clone a generic List in Java?

前端 未结 14 1962
轻奢々
轻奢々 2020-11-27 12:38

I have an ArrayList that I\'d like to return a copy of. ArrayList has a clone method which has the following signature:



        
相关标签:
14条回答
  • 2020-11-27 13:26

    Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.

    0 讨论(0)
  • 2020-11-27 13:27

    I think this should do the trick using the Collections API:

    Note: the copy method runs in linear time.

    //assume oldList exists and has data in it.
    List<String> newList = new ArrayList<String>();
    Collections.copy(newList, oldList);
    
    0 讨论(0)
提交回复
热议问题