i am new to java and was learning the concepts of hashmaps.
I am confused how the keys are sorted in hashmaps. i understood that its based on string length. but i am confused how data is sorted when the string length is 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);//SPECIFYING THE TYPE FOR FINDING HASH CODES.
//Adding values to the HashMap
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("**********************");
}
/*This method retrieves values from Map
*/
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 is
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 sorting is done in hashmap? Please help!!
Thanks in advance.