Re: [Map<Integer,ArrayList<String>>]question
Daniel Moyne wrote On 09/25/07 14:17,:
I am building a map with the key as an integer and a list of string as the
value ; basically this is the stripped code :
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.ArrayList;
public class map {
public static void main(String args[]) {
ArrayList<String>clonableDataList=new ArrayList<String>();
Map<Integer,ArrayList<String>>clonableDataMap= new
HashMap<Integer,ArrayList<String>>();
for (int i=0;i<3;i++) {
clonableDataList.removeAll(clonableDataList);
clonableDataList.add(Integer.toString(i));
clonableDataList.add(Integer.toString(i+1));
clonableDataMap.put(i,clonableDataList);
System.out.println("key="+Integer.toString(i)+"list="+clonableDataList+"**");
}
for (Map.Entry <Integer,ArrayList<String>>
entry :clonableDataMap.entrySet()) {
ArrayList<String>aa=new ArrayList<String>(entry.getValue());
System.out.println("key="+Integer.toString(entry.getKey())+"list="+entry.getValue()+"**");
}
}
}
when I run the code I get this :
key=0list=[0, 1]**
key=1list=[1, 2]**
key=2list=[2, 3]**
[2, 3]
key=2list=[2, 3]**
[2, 3]
key=1list=[2, 3]**
[2, 3]
key=0list=[2, 3]**
so apparently I get all the time the same list "2, 3" for all the the
different keys when printing my map ; what is wrong ?
Each
clonableDataMap.put(...);
enters the ArrayList object itself into the Map, not
a copy of the ArrayList's contents. The exact same
ArrayList object is entered into the Map three times,
associated with three different keys. In the three
iterations of the first loop, the lone ArrayList is
- emptied and filled with 0 and 1
- emptied again and filled with 1 and 2
- emptied again and filled with 2 and 3
After the loop on `i' the ArrayList is not changed
any more: It holds 2 and 3 from the final iteration.
Then you loop through the Map's entries and print the
single ArrayList three times, getting 2 and 3 each time.
As an experiment, add the single line
clonableDataList.add("MARVIN RULEZ");
after the second loop, and then add another copy of the
second loop. (Try to predict the output before you run
the experiment; did you predict correctly?)
--
Eric.Sosman@sun.com