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]
最简单的方法是将列表b分配给列表a
a=b
I guess you need:
a = b;
System.out.println("List values are: "+ a);
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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.