java - Every key's value is replaced with the value of the last key in my HashMap -


i'll keep short , sweet. working on project involves hashmap nesting, , i'm running issue (simplified test case):

hashmap options = new hashmap(); hashmap<string,string[]> admap = new hashmap<string,string[]>(); string[] test = new string[2]; test[0] = "oh"; test[1] = "yeah"; admap.put("test1",test); test[0] = "foo"; test[1] = "bar"; admap.put("test2",test); test[0] = "foosa"; test[1] = "barsa"; admap.put("test3",test); options.put("adlist",admap); hashmap<string,string[]> adlist = (hashmap<string,string[]>)options.get("adlist"); string[] ipport = adlist.get("test1"); system.out.println(ipport[0]+ipport[1]); 

expected output: ohyeah
real output: foosabarsa

any idea why that's happening , how fix it?

because updating same reference of test string array:

test[0] = "oh"; test[1] = "yeah"; admap.put("test1",test); test[0] = "foo"; test[1] = "bar"; admap.put("test2",test); test[0] = "foosa"; test[1] = "barsa"; 

you need create new array object before pushing map. test modification:

string[] test = new string[2]; test[0] = "oh"; test[1] = "yeah"; admap.put("test1",test);  test = new string[2]; test[0] = "foo"; test[1] = "bar"; admap.put("test2",test);  test = new string[2]; test[0] = "foosa"; test[1] = "barsa"; admap.put("test3",test); 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -