shallow copying an ArrayList in Java 5

G

Gary Newell

I need some help with Java 5.

The code snippet below worked fine in Java 1.4.2. My code makes an array
list of some predefined strings. The strings do not change, but the strings
can belong (sometime concurrently) to various groups. In Java 1.4.2, I
created the new group by copying an existing group and then modifying the
group's contents.

In Java 5, how do I "shallow copy" an ArrayList?

code:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
import java.util.*;

public class cloneArrayList {

public static void main(String args[]) {

ArrayList<String> original = new ArrayList<String>();
ArrayList<String> shallowCopy;

// initialize the array list
original.add( "StrA" );
original.add( "StrB" );
original.add( "StrC" );

// shallow copy the array list
shallowCopy = (ArrayList) original.clone();

for( int j=0; j<original.size(); j++ ) {
System.out.println( "j=" + j + ", str=" + shallowCopy.get( j ) );
}
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Output:
C:\temp>java cloneArrayList
j=0, str=StrA
j=1, str=StrB
j=2, str=StrC
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Compiler warning:
C:\temp>javac cloneArrayList.java
Note: cloneArrayList.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
C:\temp>javac -Xlint:unchecked cloneArrayList.java
cloneArrayList.java:16: warning: [unchecked] unchecked conversion
found : java.util.ArrayList
required: java.util.ArrayList<java.lang.String>
shallowCopy = (ArrayList) original.clone();
^
1 warning

Without looping through each element, how do I shallow copy the original
ArrayList?

Thanks!

Gary
 
T

Tilman Bohn

PS: Also note that you're only getting a compiler warning, not
an error. The code still compiles and works as intended.

Cheers, Tilman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top