android - How to correctly add data to a Hashmap -


i need store name , score android game , after whole day of trying shared preferences sqlite, experimenting hashmap, seems storing name , score, overwrites previous one, can have 1 @ time basically.

here code simplified show have:

map<string,integer> map = new hashmap<string,integer>(); map.put(name, scorefromgame);  (string key : map.keyset()) {      toast.maketext(getapplicationcontext(),key, toast.length_long).show();      }  (integer value : map.values()) {     toast.maketext(getapplicationcontext(), integer.tostring(value), toast.length_long).show();     } 

so name string , scorefromgame integer, once add them use loops check values stored. when go game , play again , add name , score overwrites previous one, how should adding data hashmap?

my aim store 5 scores in hashmap , names , scores shared preferences upon exiting. appreciate advice on know doing wrong, cannot make sense of documentation.

if need maintain multiple values key, you'll need map of lists:

map<string, list<integer>> values = new hashmap<string, list<integer>>(); 

this called multi-map. google collections has one.

i'd recommend encapsulate details of how done inside custom class. it'll make easier clients use.

public class multimap<k, v> {     private map<k, v> multimap = new hashmap<k, v>();      public void put(k key, v value) {         list<v> values = (this.multimap.containskey(key) ? this.multimap.get(key) : new list<v>();         if (value != null) {             values.add(value);         }         this.multimap.put(key, values);     }      public list<v> get(k key) {         list<v> values = (this.multimap.get(key) == null) ? new list<v>() : this.multimap.get(key);         return collections.unmodifiablelist(values);     } } 

Comments