user552961
user552961

Reputation: 140

Java Map question

I have one Map that contains some names and numbers

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

It works fine. I can put some values in it but when I call it in different class it gives me wrong order. For example:

I putted

abc.put("a",1);
abc.put("b",5);
abc.put("c",3);

    Iterator<String> iter = abc.keySet().iterator();

    while (iter.hasNext()) {

        String name = iter.next();
        System.out.println(name);
    }

some time it returns the order (b,a,c) and some time (a,c,b).

What is wrong with it? Is there any step that I am missing when I call this map?

Edit: I changed to HashMap and result is still same

Upvotes: 2

Views: 1232

Answers (4)

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

The only thing that's wrong is your expectations. The Map interface makes no guarantees about iteration order, and the HashMap implementation is based on hash functions which means the iteration order is basically random, and will sometimes change completely when new elements are added.

If you want a specific iteration order, you have thee options:

  • The SortedMap interfaces with its TreeMap implementation - these guarantee an iteration order according to the natural ordering of the keys (or an ordering imposed by a Comparator instance)
  • The LinkedHashMap class iterates in the order the elements were added to the map.
  • Use a List instead of a Map - this has a well-defined iteration order that you can influence in detail.

Upvotes: 5

Stan Kurilin
Stan Kurilin

Reputation: 15792

I think you need LinkedHashMap.

Upvotes: 2

AlexR
AlexR

Reputation: 115328

If you wish to get map values in the same order you used to insert them use LinkedHashMap instead.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533510

A TreeMap will always have keys in their natural order (unless you provide a comparator) If you are seeing the order any differently it will be the way you are looking at the map and what you are doing with it. If in doubt, use a debugger and you will see the order is sorted.

Upvotes: 0

Related Questions