开发者

TreeMap<Integer, String> returns an single value in java

开发者 https://www.devze.com 2023-03-05 02:05 出处:网络
TreeMap<Integer, String> map = new TreeMap<Integer, String>(); map.put(1, \"example\"); map.put(1, \"example2\");
TreeMap<Integer, String> map = new TreeMap<Integer, String>();

    map.put(1, "example");
    map.put(1, "example2");
    map.put(1, "example3");

    Iterator<Integer> itr = map.keySet().iterator();

    while (itr.hasNext()) {
        Object obj = itr.next();
        System.out.prin开发者_JS百科tln(map.get(obj));

    }

It always returns "example3". May I know why? Why can I not retrieve all the values? How are the keys in Treemap ordered? The keys should be from 0,1,2...


Because by mapping all values to the same key (1) you effectively overwrite your initial Entry. The Map javadoc says

If the map previously contained a mapping for this key, the old value is replaced by the specified value


You put different values for the same key. Instead of

map.put(1, "example");
map.put(1, "example2");
map.put(1, "example3");

use

map.put(1, "example");
map.put(2, "example2");
map.put(3, "example3");


This is because you are overwriting the value for the same key. If you had used different keys for the three, you would get all the three values. For instance, try changing to:

map.out(1, "example");
map.out(2, "example2");
map.out(3, "example3");


TreeMap<Integer, String> map = new TreeMap<Integer, String>();

    map.put(1, "example"); /*FIXED*/
    map.put(2, "example2"); /*FIXED*/
    map.put(3, "example3"); /*FIXED*/

    Iterator<Integer> itr = map.keySet().iterator();

    while (itr.hasNext()) {
        Object obj = itr.next();
        System.out.println(map.get(obj));

    }


Maps can't have duplicate keys, so you're replacing the "example" and "example2" keys. You could implement a Multimap to get around that.


That's the way Map is specified: when you add an object with the same key as an existing one, the previous value one gets overwritten.

Right from the Map's Javadoc:

A map cannot contain duplicate keys; each key can map to at most one value.

0

精彩评论

暂无评论...
验证码 换一张
取 消