How do I clone a generic List in Java?

前端 未结 14 1809
轻奢々
轻奢々 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:12

    With Java 8 it can be cloned with a stream.

    import static java.util.stream.Collectors.toList;
    

    ...

    List<AnObject> clone = myList.stream().collect(toList());
    
    0 讨论(0)
  • 2020-11-27 13:17
    ArrayList newArrayList = (ArrayList) oldArrayList.clone();
    
    0 讨论(0)
  • 2020-11-27 13:17

    This is the code I use for that:

    ArrayList copy = new ArrayList (original.size());
    Collections.copy(copy, original);
    

    Hope is usefull for you

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

    Why would you want to clone? Creating a new list usually makes more sense.

    List<String> strs;
    ...
    List<String> newStrs = new ArrayList<>(strs);
    

    Job done.

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

    This should also work:

    ArrayList<String> orig = new ArrayList<String>();
    ArrayList<String> copy = (ArrayList<String>) orig.clone()
    
    0 讨论(0)
  • 2020-11-27 13:23
    ArrayList first = new ArrayList ();
    ArrayList copy = (ArrayList) first.clone ();
    
    0 讨论(0)
提交回复
热议问题