Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add list at the end of another list (not just copy references)

I can't just modify the original list.

This is how I've seen it done:

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");

So I now would have a new list, which is a copy of the first one. And I can modify the second without the first being changed.

And now I'm having trouble understanding how to do the same, but adding the items at the end of the list.

What I though was doing exactly the above code, and adding the list to another list. With addAll for example. But I see everywhere how this only copies references and so on, so if it's inside a method or the its a rmi code the list itself wouldn't be complete, it'd get references to the other list I just created.

Since I need to do this for many types of list not sure if going item by item is ideal. So I need to add a list at the end of another list, if that's possible at all.

like image 864
keont Avatar asked May 27 '15 09:05

keont


People also ask

How do you append a list to another list in Java?

Use addAll () method to concatenate the given list1 and list2 into the newly created list.

How do you create an ArrayList from an existing list?

Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection. Syntax: ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list.

How will you copy collection into another collection?

The copy() method of java. util. Collections class is used to copy all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list.


1 Answers

addAll copies references of the elements of the source list to the end of the target list, it doesn't copy a reference to the source list itself.

This is not different from what the constructor you are using - new ArrayList<String>(l1) - does. If one meets your requirements, the other does too.

BTW, in the case of a List of an immutable class, such as String, it doesn't matter that the references to the elements are copied (as opposed to copies of the elements), since you can't modify the elements, so nothing you can do to the content of the second list will affect the content of the original list.

like image 128
Eran Avatar answered Oct 01 '22 13:10

Eran