I am new to java and have been studying hashmap concepts.
I am confused how keys are sorted in hashmaps. I realized that it is based on the length of the string. but I got confused how the data is sorted when the string length is the same.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapExample
{
public static void main(String args[])
{
Map<String,String> map = new HashMap<String,String>(20);
map.put("key value a", "test value 1");
map.put("key value b", "test value 2");
map.put("key value c", "test value 3");
System.out.println("Retrieving values from HashMap");
retrieveValuesFromListMethod(map);
System.out.println("**********************");
}
public static void retrieveValuesFromListMethod(Map map)
{
Set keys = map.keySet();
Iterator itr = keys.iterator();
String key;
String value;
while(itr.hasNext())
{
key = (String)itr.next();
value = (String)map.get(key);
System.out.println(key + " - "+ value);
}
}
}
this is my code.
output
Retrieving values from HashMap
key value c- test value 3
key value b- test value 2
key value a- test value 1
**********************
but instead of a, b, c, if I give aa, ab, ac, the output is different
Retrieving values from HashMap
key value ab - test value 2
key value aa - test value 1
key value ac - test value 3
**********************
for 1,2,3
Retrieving values from HashMap
key value 1 - test value 1
key value 2 - test value 2
key value 3 - test value 3
**********************
how is sorting done in hashmap? Please, help!
Thanks in advance.
source
share