Making Shallow Copies for Java ArrayList (Collections) Objects

This is a post on “shallow copy” versus “deep copy” and how to make a shallow copy for Java Collections objects easily. This post rises from my experiences trying to make thread local copy of arrays in building optimized java mapper.

A “shallow copy” in Java is often referred to a copy of the pointer value of a object instead of the actual contents the object is containing. In the case of an ArrayList<Elements> old, a shallow copy is another ArrayList<Elements> copy but the pointers in the ArrayList points to the same elements. That is, if you modify old.get(1), you modify copy.get(1). However, it is a separate copy of the list of pointers to the elements. if you clear the old ArrayList, the new ArrayList would retain the original pointers.


import java.util.*;

import java.io.*;

public class ArrayCopyConstructorTest{

public static void main(String[] args){

ArrayList<Integer> oldArray = new ArrayList<Integer>();

oldArray.add(1);

oldArray.add(2);

ArrayList<Integer> copyArray = new ArrayList<Integer>(oldArray);

oldArray.clear();

System.out.println("after we cleared the original array, the copy array size is " + copyArray.size());

}

}

The output size would be 2. This way of clear the original ArrayList and retain the pointers in a separate ArrayList is often used. The first ArrayList serves as a temporary buffer. The copy constructor is equivalent to


for(element : oldArrayList) newArrayList.add(element);

 

 

 

Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s