Lists are a type of collection that exists in many languages, and each language has its own way of handling them. Java’s Lists can be very useful, and with Java’s system of classes and interfaces they can be very versatile. That being said, Lists in Java can also be frustrating to deal with at times, and they are more complicated than their counterparts in a language like Python. So we’re going to talk something that can be difficult when working with Lists, copying them. Before we go any further, it is important to note that copying lists in Java is not always the best or most efficient strategy, since creating a copy can be costly both in time and space. If your List is likely to be very large, it is advisable to look for another way to way to make your program work without copying an entire list. But if you think it’s necessary, here’s how to copy a List in Java.
There are two kinds of copies, a shallow copy and a deep copy. To understand the difference, you need to understand how a List works in Java. A Lists appears to be a collection of objects, but this is not actually the case. A List is really a collection of references to objects elsewhere in memory. The reason this distinction is important is because when you copy a List normally, you’re not actually making copies of each item in the List, you’re only making a copy of the List of references. Normally, when you copy a variable, it makes an entirely new object. So if you make a copy and then change the original, it won’t affect the copy:
int myInt = 0;
int myCopy = my_int;
myInt = 1;
/*
myInt = 1
myCopy = 0
*/
The original is updated with a new value, but the original remains 0. But what happens when you try the same thing with a List?
// Create a List
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(3);
// Make a copy
ArrayList<Integer> myCopy = myList;
// Update original
myList.set(1,4);
System.out.println(myCopy);
System.out.println(myList);
[1,4,3]
[1,4,3]
This is because we only copied the references, not the objects themselves. So how do we make a copy of the entire list, objects and all? That is what is called a Deep Copy. There’s a few ways to go about this, but to keep things simple I’m just going to to go over the basic code, without using an interface or creating a new method. The easiest way to create a Deep Copy is to create a copy of each object in the original List and store it in a new List:
// Create a List
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(3);
// Make a new List
ArrayList<Integer> myCopy;
// Fill new List
for(int i: myList){
myCopy.add(i);
}
// Update original
myList.set(1,4);
System.out.println(myCopy);
System.out.println(myList);
[1,2,3]
[1,4,3]
Now we have a distinct copy that is unaffected by changes to the original List. Next time, we’ll go discuss how to copy a List of Lists.
Top comments (0)