How do I clone a generic List in Java?

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

    I find using addAll works fine.

    ArrayList<String> copy = new ArrayList<String>();
    copy.addAll(original);
    

    parentheses are used rather than the generics syntax

    0 讨论(0)
  • 2020-11-27 13:07
    List<String> shallowClonedList = new ArrayList<>(listOfStrings);
    

    Keep in mind that this is only a shallow not a deep copy, ie. you get a new list, but the entries are the same. This is no problem for simply strings. Get's more tricky when the list entries are objects themself.

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

    I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).

     public static <T extends Object> List<T> clone(List<T> list) {
          try {
               List<T> c = list.getClass().newInstance();
               for(T t: list) {
                 T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
                 c.add(copy);
               }
               return c;
          } catch(Exception e) {
               throw new RuntimeException("List cloning unsupported",e);
          }
    }
    
    0 讨论(0)
  • 2020-11-27 13:09

    Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.

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

    If you want this in order to be able to return the List in a getter it would be better to do:

    ImmutableList.copyOf(list);
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题