Home java Copy ArrayList

Copy ArrayList

Author

Date

Category

There is ArrayList with values.
Question: How can I completely copy the value of the array without cycles?

arraylist a;
ArrayList B;
a = b; // Assign all the values ​​of b to this array.

Answer 1, Authority 100%

  1. You can using the collections.copy (destination, source) (minus is that you need to set ArrayList B the desired size, otherwise it will be swear):

    collections.copy (b, a);
    
  2. with Clone () (Example on ideone ):

    arraylist & lt; string & gt; B = (ArrayList & LT; String & GT;) a.clone ();
    
  3. using the designer:

    arraylist & lt; string & gt; a;
    ArrayList & LT; String & GT; B = new ArrayList & LT; String & GT; (a);
    
  4. Using the AddALL () :

    arraylist & lt; string & gt; a;
    ArrayList & LT; String & GT; B = New ArrayList & LT; String & GT; ();
    B.Addall (0, A);
    

Answer 2, Authority 56%

arraylist & lt; string & gt; a = new arraylist (array.aslist ("ABC", "MNO"));
ArrayList & LT; String & GT; b;
B = (ArrayList & LT; String & GT;) a.clone ();

and you can still:

arraylist & lt; string & gt; B = new ArrayList & LT; String & GT; (a);

Answer 3, Authority 28%

arraylist a;
ArrayList B;
a = b. clone ();

Answer 4, Authority 6%

The sheet stores links to objects, so they are copied precisely, i.e. Through a new sheet, you work with old objects in fact. If you want to transfer to copy the values, you first need to create a new object for storing the value using the New statement.

For example:

arraylist & lt; string & gt; TOCOPY = NEW ArrayList & LT; & GT; ();
Tocopy.add ("Something");
ArrayList & LT; String & GT; Copy = New ArrayList & lt; & gt; ();
Copy.Add (New String (Tocopy.get (0)));

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions