Wednesday 15 May 2013

java - Hashmap receives true instead of ArrayList -



java - Hashmap receives true instead of ArrayList -

so turns out working (i'm not senior developer yet can see) while out of bluish realized wrong code. hashmap receives "true" instead of receiving arraylist 1 object in first position. matter of illustration can see i'm talking follows:

product item = new product(); map rmap = new hashmap(); rmap.put("productslist", new arraylist().add(item));

after lines of code, , coding helpermethods attempted retrieve "productslist" map couldn't so, didn't know why after debugging found out when set done, there no such list, boolean value. way retrieved follows:

if (rmap.containskey("productslist")) { // if statement beingness skipped because of boolean if (rmap.get("productslist") instanceof arraylist) { list<product> pr = (list) rmap.get("productslist"); } }

on other hand i've got (which way more clear) , woks expected:

product item = new product(); map rmap = new hashmap(); list < product > mylist = new arraylist(); mylist.add(item); rmap.put("productslist", mylist);

what done in order cut down 2 lines of code list created , object set list? it's not big deal of course, it's want create coding clearer , staightforward.

you can utilize arrays#aslist method this

map.put("productlist", arrays.aslist(item1, item2, item3));

also suggest utilize generics, type-safety in exchange.

map<string, list<string>> rmap = new hashmap<string, list<string>>(); rmapu.put("productlist", arrays.aslist("item1", "item2"));

java arraylist constructor

No comments:

Post a Comment