Java ArrayList copy

2019-01-01 10:47发布

I have an ArrayList l1 of size 10. I assign l1 to new list reference type l2. Will l1 and l2 point to same ArrayList object? Or is a copy of the ArrayList object assigned to l2?

When using the l2 reference, if I update the list object, it reflects the changes in the l1 reference type also.

For example:

List<Integer> l1 = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
    l1.add(i);
}

List l2 = l1;
l2.clear();

Is there no other way to assign a copy of a list object to a new reference variable, apart from creating 2 list objects, and doing copy on collections from old to new?

6条回答
伤终究还是伤i
3楼-- · 2019-01-01 10:55

Yes l1 and l2 will point to the same reference, same object.

If you want to create a new ArrayList based on the other ArrayList you do this:

List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");

The result will be l1 will still have 2 elements and l2 will have 3 elements.

查看更多
何处买醉
4楼-- · 2019-01-01 10:58

Java doesn't pass objects, it passes references (pointers) to objects. So yes, l2 and l1 are two pointers to the same object.

You have to make an explicit copy if you need two different list with the same contents.

查看更多
路过你的时光
5楼-- · 2019-01-01 11:04

Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:

ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);

This is actual copying of values and not just copying of reference.

查看更多
栀子花@的思念
6楼-- · 2019-01-01 11:06

There is a method addAll() which will serve the purpose of copying One ArrayList to another.

For example you have two Array Lists: sourceList and targetList, use below code.

targetList.addAll(sourceList);

查看更多
冷夜・残月
7楼-- · 2019-01-01 11:08

Yes, assignment will just copy the value of l1 (which is a reference) to l2. They will both refer to the same object.

Creating a shallow copy is pretty easy though:

List<Integer> newList = new ArrayList<>(oldList);

(Just as one example.)

查看更多
登录 后发表回答