2
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.println(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...

6 Answers 6

6

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

Sign up to request clarification or add additional context in comments.

Comments

3

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");

Comments

2

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");

Comments

2
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));

    }

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.