Re: Confused with the ArrayList
On Thu, 23 Aug 2007 05:21:26 -0700, dshankhoon@gmail.com wrote, quoted
or indirectly quoted someone who said :
Hello,
I have converted your snippet to an SSCCE.
see http://mindprod.com/jgloss/sscce.html
I have also added some generics to make it clearer
what you are doing.
I have renamed your temp variables to make it clear
they are distinct.
I have added some labelling of the output.
You did not ask a question. Presumably you were expecting different
output than what you got. To me there were no surprises. Perhaps my
comments will explain what was troubling you.
import java.util.ArrayList;
import static java.lang.System.out;
public class CopyConfusion
{
/**
* main startup method
* @param args not used
*/
public static void main ( String [] args )
{
ArrayList<ArrayList<String>> original = new
ArrayList<ArrayList<String>>();
ArrayList<String> copy = new ArrayList<String>();
copy.add("Test1");
copy.add("Test2");
original.add(copy);
copy = new ArrayList<String>();
copy.add("Test3");
copy.add("Test4");
// this adds the entire ArrayList as a single element, not the
individual Strings.
original.add(copy);
// original contains two ArrayLists at this point, each with two
Strings.
out.println(">>>temp1");
for ( int i=0;i<original.size();i++ )
{
final ArrayList<String> temp1 = original.get(i);
for ( int j=0;j<temp1.size();j++ )
{
out.println(temp1.get(j));
}
}
// output is
// >>>temp1
// Test1
// Test2
// Test3
// Test4
// The following code modifies the ArrayLists in the original.
// Perhaps you were expecting get to hand you a clone rather
// than the actual element.
// Note that the for loop starts at 1 rather than 0.
// This means you will leave original[0] intact.
for ( int i=1;i<original.size();i++ )
{
final ArrayList<String> temp2 = original.get(i);
temp2.set(0,"Test5");
temp2.set(1,"Test6");
}
out.println(">>>temp3");
for ( int i=0;i<original.size();i++ )
{
final ArrayList<String> temp3 = original.get(i);
for ( int j=0;j<temp3.size();j++ )
{
out.println(temp3.get(j));
}
}
// output is
// >>>temp3
// Test1
// Test2
// Test5
// Test6
}
}
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com