-2

Okay so I've done some research on this and am stuck. I understand now that the list just holds pointers to the hashmap so I end up with 5 pointers to the same value. I cannot for the life of me think of any way to get around this problem. How can i store the values and keep them? I tried using String.valueOf() but that is a pointer as well apparently.

List<HashMap<String,String>> tbcPackages = new ArrayList<HashMap<String,String>>();

JSONObject g = new JSONObject();

for(int i = 0; i <5 ; i++){

    g.clear();

    System.out.println("clear? : " + g);

    g.put("test", i);

    tbcPackages.add(g); 

    System.out.println(tbcPackages);

}
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29
Tim Willis
  • 140
  • 10

1 Answers1

2

The problem occurs because you are using same object "JSONObject g". At every iteration of loop, create a new object. The modified code given below:

List<HashMap<String,String>> tbcPackages = new 
ArrayList<HashMap<String,String>>();

for(int i = 0; i <5 ; i++){
  JSONObject g = new JSONObject();
  g.clear();

  System.out.println("clear? : " + g);

  g.put("test", i);

  tbcPackages.add(g); 
  System.out.println(tbcPackages);
}
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29