2

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.

4

1 回答 1

3

如果您需要为一个键维护多个值,则需要一个列表映射:

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

这称为多地图。谷歌收藏有一个。

我建议您将如何在自定义类中完成此操作的详细信息封装起来。这将使客户更容易使用。

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);
    }
}
于 2013-05-05T23:37:58.007 回答