java - How to store multiple objects from a hashmap that has the same key? -
edit
i've tried hashmap multiple values under same key, , hashmap looks hashmap<string, list<place>> placemap = new hashmap<>();
also tried put object instead of place(place superclass). when create subclasses , wants add them hashmap get:
the method put(string, list) in type
hashmap<string,list<place>>
not applicable arguments (string, namedplace)
and
the method put(string, list) in type
hashmap<string,list<place>>
not applicable arguments (string, descplace)
here adding created error:
namedplace p = new namedplace(x,y,answer,col,cat); placemap.put(answer, p);
descplace dp = new descplace(x,y,answer, desc, col, cat); mp.add(dp); placemap.put(answer, dp);
namedplace , descplace both subclasses place, , want them both in same hashmap..
op
i'm working on little project here. thing need use hashmap instead of arraylist on part of project because hashmap alot faster searching. i've created hashmap this:
hashmap<string, object> placemap = new hashmap<>();
the string name of object, thing more 1 object can have same name. search object in searchfield , want store objects has name arraylist can change info in them.
the object have alot of different values, name, position, booleans etc.
do need create hashcode method object class shall create unique hashcode?
when using standard map<string, list<yourclasshere>>
instance, important remember map's values each entry list<yourclasshere>
, , not handle in special way. in case, if have
private map<string, list<place>> placemap = new hashmap<>();
then store values need follows:
namedplace p = new namedplace(x,y,answer,col,cat); list<place> list = placemap.get (answer); list.add(p);
however, piece of code has underlying problems.
- it doesn't take account
answer
might not present inplacemap
. - it assumes there's
list<place>
instance each key query.
so best way fix potential problems follows (java 7 , later):
namedplace p = new namedplace(x,y,answer,col,cat); if (placemap.containskey (answer) && placemap.get (answer) != null) { placemap.get (answer).add(p); } else { list<place> list = new arraylist<place> (); // ..or whatever list implementation need list.add (p); placemap.put (answer, list); }
if want scna through list of places, code this:
if (placemap.containskey (key) && placemap.get (answer) != null) { (place p: placemap.get (key)) { // stuff } }
Comments
Post a Comment