# HashMap - Urgent

Hi,

I am learning maps and i ran the program below which gives me :

{E542=Brendan, E123=Charles, E174=Tobin}

I find this strange as at first i thought it was printing based on the asending order. But later, when I changed E174 to to Aaa. it still prints:
{E542=Brendan, E123=Charles, E174=Aaa}

Pls clarify. how does the hash map prints number ?

import java.util.*;
public class MapTest1 {
public static void main(String[] args) {
// Hasp map mapping employee number to accounts
Map accountsMap = new HashMap();
accountsMap.put("E123","Charles");
accountsMap.put("E174","Matt");
accountsMap.put("E542","Brendan");
accountsMap.put("E174","Tobin");
System.out.println(accountsMap);
}
}
###### Who is Participating?

Commented:
HashMap is unordered. Use TreeMap for sorted keys, LinkedHashMap for order of addition
0

Author Commented:
but how do you know, what is printed out first.

It could have been : {E123=Charles, E542=Brendan, E174=Tobin}

as i entered charles first, then brendan lastly tobin.
0

Commented:
In case it's not clear, any ordering is based on keys, not values
0

Commented:
>>but how do you know, what is printed out first.

You don't. It's unordered
0

Commented:
If you need to know, use one of the approaches i mentioned at first
0

Author Commented:
Hi,

I looked at the tut above and got this:

import java.util.HashMap;
import java.util.Map;

public class MainClass {
public static void main(String[] a) {

Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");

System.out.println(map);
}
}

{key1=value1, key3=value3, key2=value2}

Similarly, key 1 is printed than key3 and lastly key2.
>>
>>CEHJ:
>>In case it's not clear, any ordering is based on keys, not values

This part i am confused. Since ordering is done based on keys, it should have key 1 then, key 2 and lastly key3.

Sorry, I am a bit too slow to understand..
0

Commented:
Order is *not* done on key for a HashMap. It is an unordered collection, ie. the order can be whatever it wants to be.
Try a TreeMap, it does order on key.
0

Commented:
>>This part i am confused. Since ordering is done based on keys, it should have key 1 then, key 2 and lastly key3.

Only in a TreeMap
0

Commented:
>     Map map = new HashMap();

change to:

Map map = new TreeMap();
0

Commented:
Map map = new TreeMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
0

Author Commented:
Got it . thank you very much. :-)
0

Commented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.