deucalion0
deucalion0

Reputation: 2440

How to correctly add data to a Hashmap

I need to store a name and score for my android game and after a whole day of trying everything from shared preferences to SQLite, I am now experimenting with a HashMap, which seems to be storing my name and score, but it always overwrites the previous one, I can only have one at a time basically.

Here is my code simplified to show you what I have:

Map<String,Integer> map = new HashMap<String,Integer>();
map.put(name, scorefromgame);

for (String key : map.keySet()) {
     Toast.makeText(getApplicationContext(),key, Toast.LENGTH_LONG).show();
     }

for (Integer value : map.values()) {
    Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_LONG).show();
    }

So name is a string and scorefromgame is an integer, once I add them I use the for loops to check the values are stored. When I go back to my game and play again and add another name and score it overwrites the previous one, how should I be adding data to the HashMap?

My aim is to store five scores in the HashMap and then the names and scores to shared preferences upon exiting. I would appreciate any advice on this as I know I am doing this wrong, but I cannot make sense of the documentation.

Upvotes: 2

Views: 6892

Answers (1)

duffymo
duffymo

Reputation: 308753

If you need to maintain multiple values for a key, you'll need a Map of Lists:

Map<String, List<Integer>> values = new HashMap<String, List<Integer>>();

This is called a multi-map. Google Collections has one.

I'd recommend that you encapsulate the details of how this is done inside a custom class. It'll make it easier for clients to 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);
    }
}

Upvotes: 3

Related Questions