Reputation: 2311
I have two array lists, Can it possible to replace the one list items with the second list.
ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = new ArrayList<String>();
a.add("testone");
a.add("testtwo");
a.add("testthree");
b.add("demoone");
b.add("demotwo");
System.out.println("List values are: "+ a);
Is there any way to replace the first list with the second list elements. So if I print first array list, it should print the following output
[demoone, demotwo]
Upvotes: 0
Views: 1959
Reputation: 29
So there are two ways to do this based on requirement.
You need the list referenced by reference variable b
to be available with the reference variable a
. In this case the original list referenced by a
is not required to be modified, just the reference variable a
is being pointed to the second list (originally referenced by reference variable b
).
a = b;
System.out.println("List values are: "+ a);
You need the list referenced by reference variable a
to have the items present in the list referenced by b
. In this case, the actual list originally referenced by a
has to be modified. This might be required when you are passing the list to a method which is supposed to modify the list.
a.clear();
a.addAll(b);
System.out.println("List values are: "+ a);
Upvotes: 2
Reputation:
Option 1:
a = b; //copy same list reference
Option 2:
a.clear(); //clear all existing items
a.addAll(b); //copy all
Option 3:
a = (ArrayList<String>)b.clone(); //shallow copy
Upvotes: 3
Reputation: 62864
I guess you need:
a = b;
System.out.println("List values are: "+ a);
Upvotes: 3