I have a Map containing Strings for keys and Lists as values. After putting several entries into the Map and randomly expanding the List values in the Map I get the following problem:
list3 = map.get("string1");
list3.get(0).setName("testobject");
for(TestObject to : list3){
System.out.println(to.getName());
}
Instead of only setting the first TestObject with name “testobject” it also sets other TestObjects in the List (list3) with the name “testobject”, ie:
**Output**
testobject
nonameset
nonameset
nonameset
testobject
nonameset
nonameset
nonameset
testobject
nonameset
Full code is written underneath. I guess the problem has something to do with randomly expanding the List values in the map (randomlyExpand function) and referencing, but as my Java knowledge is still beginning to develop, I do not really understand what is happening. It’s probably something really stupid. So my question is: what is going on here? And how can I fix the problem while retaining same functionality.
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String, List<TestObject>> map = new HashMap<String, List<TestObject>>();
List<TestObject> list1 = new ArrayList<TestObject>();
List<TestObject> list2 = new ArrayList<TestObject>();
List<TestObject> list3 = new ArrayList<TestObject>();
for(int i = 0; i < 5; i++){
list1.add(new TestObject());
}
for(int i = 0; i < 5; i++){
list2.add(new TestObject());
}
map.put("string1", list1);
map.put("string2", list2);
map = randomlyExpand(map);
list3 = map.get("string1");
list3.get(0).setName("testobject");
for(TestObject to : list3){
System.out.println(to.getName());
}
}
//Randomly expand list values in Map from size 5 to size 10
public static Map<String, List<TestObject>> randomlyExpand(Map<String, List<TestObject>> map){
Random ran = new Random();
for (String key : map.keySet()){
List<TestObject> tempList = new ArrayList<TestObject>();
List<TestObject> values = map.get(key);
for (int i = 0; i < 10; i++){
int randomInt = ran.nextInt(values.size());
tempList.add(values.get(randomInt));
}
map.put(key, tempList);
}
return map;
}
}
TestObject class:
public class TestObject {
private String name = "nonameset";
TestObject(){
}
public String getName(){
return this.name;
}
public void setName(String s){
this.name = s;
}
}
The problem is in your
randomlyExpandfunction. You are iterating trough your list of 5 distinguished objects that you have previously created with this:Now you are doing this:
You are getting one of this distinguished objects and you add it again on another index. Now this single objects occurs two times in your list (or even more). So you have the same object multiple times in the list. That’s way you see or object multiple times.
The solution is simple: create new objects in your loop.