Search code examples
anylogic

Handle LinkedHashMap. How update array of a particular key


I have a problem with linkedHashMap. I built a collection as follows:

int v[]={0,0,0,0,0};
collection.put("A",v);
collection.put("B",v);
collection.put("C",v);
collection.put("D",v);

I have agents with two parameters: p1 is a value between ("A","B","C","D") and p2 an integer value between (0 and 4).For each agent that enters the flow I want to update the collection to the key P1 at the position of the index indicated by P2. The code I wrote to do it is as follows:

collection.get(agent.P1)[agent.P2]++;

The error is as follows: The increment is at the correct location, but for all keys. The output obtained is in image attached

enter image description here


Solution

  • Well, think about it: you change v. But v appears in all of your collection's values, it is the same v. (google "Java pass by reference versuc value"). So if you change v in one place, all other places "looking at" v will also find it changed.

    To "split them up", you need to instantiate your collection differently, such that each value is its own int array:

    collection.put("A",new int[]{0,0,0,0});
    collection.put("B",new int[]{0,0,0,0});
    collection.put("C",new int[]{0,0,0,0});
    collection.put("D",new int[]{0,0,0,0});