How to copy values, not references, of List into another list?

前端 未结 7 1704
-上瘾入骨i
-上瘾入骨i 2021-01-31 18:52

Namely, without referencing the same object, I need to copy values of elements of one list into another list. These are the lists:

List listA = ne         


        
相关标签:
7条回答
  • 2021-01-31 19:29
    List<XObject> lista = new ArrayList();
    List<XObject> listb = new ArrayList();
    
    //copy no reference
    lista.adAll(new ArrayList<>(listb));
    

    This code block works for me!

    0 讨论(0)
  • 2021-01-31 19:33

    Try to use this, while the answers given by another guys are totally fine. But per my option, the following would be the best way:

    List<Integer> listB = new ArrayList<Integer>(listA); 
    
    0 讨论(0)
  • 2021-01-31 19:37

    There is absolutely no reason to make a copy of an Integer. Integer is an immutable class. This means that its value is set when the Integer instance is created, and can never change. An Integer reference can thus be shared by multiple lists and threads without fear, because there's no way anybody can change its value. Your question thus makes no real sense.

    To create an ArrayList b containing the same Integers as another List a, just use the following code:

    List<Integer> b = new ArrayList<Integer>(a);
    

    Sure the Integer won't be cloned, but this is a good thing, because cloning them is completely unnecessary.

    0 讨论(0)
  • 2021-01-31 19:39

    Try This.

    ListB.addAll(listA);
    
    0 讨论(0)
  • 2021-01-31 19:41

    You can try and give a look at the Collections.copy method:

    public static void copy(List dest, List src)

    Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. This method runs in linear time.

    Parameters: dest - The destination list. src - The source list.

    Note: The above should work for simple data types such as Integers, however, if you have your own objects which might in turn reference other objects, you will have to iterate over each object and copy it separately.

    0 讨论(0)
  • 2021-01-31 19:50

    Use this method of Collections class to copy all elements of ArrayList to another ArrayList:

    Collections.copy(listA, listB); 
    
    0 讨论(0)
提交回复
热议问题