How do I clone a generic List in Java?

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

    To clone a generic interface like java.util.List you will just need to cast it. here you are an example:

    List list = new ArrayList();
    List list2 = ((List) ( (ArrayList) list).clone());
    

    It is a bit tricky, but it works, if you are limited to return a List interface, so anyone after you can implement your list whenever he wants.

    I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with List -the generic parent- not ArrayList

提交回复
热议问题