2

I am getting some weird results and can't explain them. Do you have an Idea, why I get

> {Level=1 - Normal, Name=IT/Java} 
> {Level=2 - Medium, Name=IT/Ruby}
> [{Level=2 - Medium, Name=IT/Ruby}, {Level=2 - Medium, Name=IT/Ruby}]

from the sysos? when it should actually be

> {Level=1 - Normal, Name=IT/Java} 
> {Level=2 - Medium, Name=IT/Ruby}
> [{Level=1 - Normal, Name=IT/Java}, {Level=2 - Medium, Name=IT/Ruby}]

Here's my Code.

public List<Map<String, Object>> getMapsforTables() {
        levelList = this.getSkilllevel();
        description = this.getSkillnames();
        Map<String, Object> rm = new HashMap<String, Object>();
        List<Map<String, Object>> l = new LinkedList<Map<String, Object>>();

        for(int i=0; i < levelList.size(); i++){
            rm.clear();
            rm.put("Name", description.get(i));
            rm.put("Level", levelList.get(i));
            System.out.println(rm);
            l.add(rm);
        }
        System.out.println(l);
        return l;
    }
Saggex
  • 3,390
  • 3
  • 22
  • 37
  • 4
    Please learn what objects and references are - you keep changing an object whilst already placing it in another object and wonder that something changes afterwards. – Smutje Jan 12 '15 at 14:44

3 Answers3

5

Because on each iteration, you're modifying and adding the same object to the list. You could do:

for(int i = 0; i < levelList.size(); i++){
    Map<String, Object> rm = new HashMap<String, Object>();
    rm.put("Name", description.get(i));
    rm.put("Level", levelList.get(i));
    System.out.println(rm);
    l.add(rm);
}
fardjad
  • 20,031
  • 6
  • 53
  • 68
3

The short version is because you're re-using the same Map object over and over again.

Move the Map<String, Object> rm = new HashMap<String, Object>(); line inside the for loop, as the first statement and your issue should go away.

In the longer term, you should look at some general CS or java tutorial on the difference between pass-by-reference and pass-by-value.

Daniel Martin
  • 23,083
  • 6
  • 50
  • 70
2

What happens is that when you add the element to the List:

l.add(rm);

you are adding a reference to an object.

In the next iteration, you are modifying the object that rm refers to, and you add it again. So, you added the same reference twice.

What can you do?

A simple solution would be to declare rm inside the loop:

for(int i=0; i < levelList.size(); i++){
    Map<String, Object> rm = new HashMap<String, Object>();
    ...
}
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73