How do I copy the contents of one ArrayList into another?

后端 未结 12 1637
傲寒
傲寒 2020-11-27 10:46

I have some data structures, and I would like to use one as a temporary, and another as not temporary.

ArrayList myObject = new ArrayList

        
                      
相关标签:
12条回答
  • 2020-11-27 11:08

    Suppose you have two arraylist of String type . Like

    ArrayList<String> firstArrayList ;//This array list is not having any data.
    
    ArrayList<String> secondArrayList = new ArrayList<>();//Having some data.
    

    Now we have to copy the data of second array to first arraylist like this,

    firstArrayList = new ArrayList<>(secondArrayList );
    

    Done!!

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

    You can use such trick:

    myObject = new ArrayList<Object>(myTempObject);
    

    or use

    myObject = (ArrayList<Object>)myTempObject.clone();
    

    You can get some information about clone() method here

    But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.

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

    Supopose you want to copy oldList into a new ArrayList object called newList

    ArrayList<Object> newList = new ArrayList<>() ;
    
    for (int i = 0 ; i<oldList.size();i++){
        newList.add(oldList.get(i)) ;
    }
    

    These two lists are indepedant, changes to one are not reflected to the other one.

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

    You need to clone() the individual object. Constructor and other methods perform shallow copy. You may try Collections.copy method.

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

    to copy one list into the other list, u can use the method called Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.

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

    Straightforward way to make deep copy of original list is to add all element from one list to another list.

    ArrayList<Object> originalList = new ArrayList<Object>();
    ArrayList<Object> duplicateList = new ArrayList<Object>();
    
    for(Object o : originalList) {
        duplicateList.add(o);
    }
    

    Now If you make any changes to originalList it will not impact duplicateList.

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