Copying an ArrayList

There are ArrayList with values.
Question: how can I completely copy an array value without loops?

ArrayList a;
ArrayList b;

a = b;// Присвоить все значения b в этот массив. 
Author: Denis, 2016-08-31

4 answers

  1. You can use the method Collections.copy(destination, source) (the disadvantage is that you need to set the ArrayList b of the desired size, otherwise it will swear):

    Collections.copy(b,a);
    
  2. Using clone() (example on ideone):

    ArrayList<String> b = (ArrayList<String>)a.clone();
    
  3. Using the constructor:

    ArrayList<String> a;
    ArrayList<String> b = new ArrayList<String>(a);
    
  4. Using the method addAll():

    ArrayList<String> a;
    ArrayList<String> b = new ArrayList<String>();
    b.addAll(0, a);
    
 17
Author: Denis, 2016-08-31 13:47:48
ArrayList<String> a = new ArrayList(Arrays.asList("abc", "mno"));
ArrayList<String> b;
b = (ArrayList<String>) a.clone();

And you can still do this:

ArrayList<String> b = new ArrayList<String>(a);
 10
Author: Ksenia, 2016-08-31 11:04:57
ArrayList a;
ArrayList b;

a=b.clone();
 5
Author: Komdosh, 2016-08-31 10:56:21

The sheet stores references to objects, so they are copied, i.e. through the new sheet you actually work with the old objects. if you want to transfer or copy values, you first need to create a new object to store the value using the new operator.

For example:

ArrayList<String> toCopy = new ArrayList<>();

toCopy.add("Something");

ArrayList<String> copy = new ArrayList<>();

copy.add(new String(toCopy.get(0)));
 0
Author: Сергей Васильев, 2019-12-10 20:23:41