Copying arraylist to an arraylist in java

Copy Elements of One ArrayList to Another ArrayList in Java

In this tutorial, we will write a java program to copy elements of one ArrayList to another ArrayList in Java. We will be using addAll() method of ArrayList class to do that.

public boolean addAll(Collection c)

When we call this method like this:

It appends all the elements of oldList to the newList . It throws NullPointerException , if oldList is null.
Note: This method doesn’t clone the ArrayList, instead it appends the elements of one ArrayList to another ArrayList.

Copy elements from one ArrayList to another ArrayList

In the following example, we have an ArrayList al that contains three elements. We have another List list that contains some elements, we are copying the elements of list to the al . This is done using addAll() method, which copies the elements of one List to another another list. This operation doesn’t remove the existing elements of the list, in which the elements are copied.

import java.util.ArrayList; import java.util.List; public class ListToArrayListExample < public static void main(String a[])< ArrayListal = new ArrayList(); //Adding elements to the ArrayList al.add("Text 1"); al.add("Text 2"); al.add("Text 3"); System.out.println("ArrayList Elements are: "+al); //Adding elements to a List List list = new ArrayList(); list.add("Text 4"); list.add("Text 5"); list.add("Text 6"); //Adding all elements of list to ArrayList using addAll al.addAll(list); System.out.println("Updated ArrayList Elements: "+al); > >
ArrayList Elements are: [Text 1, Text 2, Text 3] Updated ArrayList Elements: [Text 1, Text 2, Text 3, Text 4, Text 5, Text 6]

Recommended Articles:

Читайте также:  Pillow python создание изображения

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

@ Himanshu, ArrayList never be a null, instead it is an empty when u create. if you want more clarity, execute the below code. List list = new ArrayList();
List newList = new ArrayList();
list.addAll(newList);
System.out.println(list); // this works fine and creates a list with empty List list = null;
List newList = null;
list.addAll(newList);
System.out.println(list); // this will give you NPE. since List is not initiated with any of its implemented class

Источник

Java ArrayList copy

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 l1 = new ArrayList(); for (int i = 1; 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?

10 Answers 10

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 newList = new ArrayList<>(oldList); 

Is it possible to copy only a part of an arraylist to a new arraylist, Efficiently. for eg: copy elements between position 5 and 10 from one arraylist to another new arraylist. In my application the range would be much bigger.

@Ashwin: Well it’s an O(N) operation, but yes. you can use List.subList to get a «view» onto a section of the original list.

what if the array lists are nested (ArrayList) ? would this recursively create copies of all children ArrayList objects?

@ShanikaEdiriweera: You could do it in a fluent way with streams, yes. But the tricky part is creating a deep copy, which most objects won’t provide. If you have a specific case in mind, I suggest you ask a new question with details.

@atc it’s one more way to do shallow copy, instead of new ArrayList() it’s used another algorithm and can be used for any List implementation, not just for an ArrayList, that is all 🙂

This method is very misleading! Actually, it’s description is. It says: «copies elements from one source list into the destination», but they are not copied! They are referenced so there will only be 1 copy of the objects and if they are mutable, you’re in trouble

This answer doesn’t make a whole lot of sense. Collections.copy is not at all an alternative to new ArrayList<>(source) . What Collections.copy actually does is assume that destination.size() is at least as big as source.size() , and then copy the range index-by-index using the set(int,E) method. The method doesn’t add new elements to the destination. Refer to the source code if it’s not clear enough from the Javadoc.

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 l1 = new ArrayList(); l1.add("Hello"); l1.add("World"); List l2 = new ArrayList(l1); //A new arrayList. l2.add("Everybody"); 

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

@MortalMan the difference is that l2 = new ArrayList(l1) is an entirely new object and modifying l2 doesn’t affect l1, whereas List l2 = l1 you are not creating a new object but just referencing the same object as l1, so in this case doing an operation such as l2.add(«Everybody»), l1.size() and l2.size() will return 3 because both are referencing the same object.

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

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

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

This answer is wrong. addAll() just copies the references as invertigo said. This is not a deep copy.

For an ArrayList this answer is acceptable because String is immutable, but try it with the OP’s example, an ArraList, and you’ll see it is just copying references.

Just not my day I guess. It turns out classes such as Integer and Long are also immutable, so Harshal’s answer works for simple cases such as ArrayList and ArrayList. Where it fails is for complex objects that are not immutable.

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

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.

List.copyOf ➙ unmodifiable list

Is there no other way to assign a copy of a list

Java 9 brought the List.of methods for using literals to create an unmodifiable List of unknown concrete class.

LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ; List < LocalDate >dates = List.of( today.minusDays( 1 ) , // Yesterday today , // Today today.plusDays( 1 ) // Tomorrow ); 

Along with that we also got List.copyOf . This method too returns an unmodifiable List of unknown concrete class.

List < String >colors = new ArrayList<>( 4 ) ; // Creates a modifiable `List`. colors.add ( "AliceBlue" ) ; colors.add ( "PapayaWhip" ) ; colors.add ( "Chartreuse" ) ; colors.add ( "DarkSlateGray" ) ; List < String >masterColors = List.copyOf( colors ) ; // Creates an unmodifiable `List`. 

By “unmodifiable” we mean the number of elements in the list, and the object referent held in each slot as an element, is fixed. You cannot add, drop, or replace elements. But the object referent held in each element may or may not be mutable.

colors.remove( 2 ) ; // SUCCEEDS. masterColors.remove( 2 ) ; // FAIL - ERROR. 

dates.toString(): [2020-02-02, 2020-02-03, 2020-02-04]

colors.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]

masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]

You asked about object references. As others said, if you create one list and assign it to two reference variables (pointers), you still have only one list. Both point to the same list. If you use either pointer to modify the list, both pointers will later see the changes, as there is only one list in memory.

So you need to make a copy of the list. If you want that copy to be unmodifiable, use the List.copyOf method as discussed in this Answer. In this approach, you end up with two separate lists, each with elements that hold a reference to the same content objects. For example, in our example above using String objects to represent colors, the color objects are floating around in memory somewhere. The two lists hold pointers to the same color objects. Here is a diagram.

enter image description here

The first list colors is modifiable. This means that some elements could be removed as seen in code above, where we removed the original 3rd element Chartreuse (index of 2 = ordinal 3). And elements can be added. And the elements can be changed to point to some other String such as OliveDrab or CornflowerBlue .

In contrast, the four elements of masterColors are fixed. No removing, no adding, and no substituting another color. That List implementation is unmodifiable.

Источник

How do I copy the contents of one ArrayList into another?

I have some data structures, and I would like to use one as a temporary, and another as not temporary.

ArrayList myObject = new ArrayList(); ArrayList myTempObject = new ArrayList(); //fill myTempObject here . //make myObject contain the same values as myTempObject myObject = myTempObject; //free up memory by clearing myTempObject myTempObject.clear(); 

now the problem with this of course is that myObject is really just pointing to myTempObject , and so once myTempObject is cleared, so is myObject . How do I retain the values from myTempObject in myObject using java?

You can use List.addAll . But if you need to retain all the objects then clearing the temp list is not really going to clear a whole lot of memory. Because your are only trying to clear the references, as far as objects you are trying to keep them.

13 Answers 13

myObject = new ArrayList(myTempObject); 
myObject = (ArrayList)myTempObject.clone(); 

You can get some information about clone() method here

But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.

assign by value in Java is something that is reserved for primitive types (int, byte, char, etc.) and literals. Unless you explicitly tell Java to copy something that is derived from Object it’ll always assign by reference. By the way clone() is a shallow copy and will not copy the contained Objects but rather references to them. If you want to make a deep-copy take a look at: stackoverflow.com/questions/64036/…

@PeterT — Java is only call by and assign by value. Non-primitive type variables contain reference values which are assigned or passed.

@X09 oldList = newList will copy reference of the newList to oldList, any change in newList will be reflected in the oldList also. That is not the intended behaviour.

originalArrayList.addAll(copyArrayList);

Please Note: When using the addAll() method to copy, the contents of both the array lists (originalArrayList and copyArrayList) refer to the same objects or contents. So if you modify any one of them the other will also reflect the same change.

If you don’t wan’t this then you need to copy each element from the originalArrayList to the copyArrayList, like using a for or while loop.

There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use = you’re only coping that value.

In order to preserve the contents of myTempObject you would need to make a copy of it.

This can be done by creating a new ArrayList using the constructor that takes another ArrayList :

ArrayList myObject = new ArrayList(myTempObject); 

Edit: As Bohemian points out in the comments below, is this what you’re asking? By doing the above, both ArrayList s ( myTempObject and myObject ) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject then you would need to make a copy of each individual object in the original ArrayList

Источник

Оцените статью