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 map = new HashMap(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.
解决方案
java.util.HashMap is unordered; you can't and shouldn't assume
anything beyond that.
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant
over time.
java.util.LinkedHashMap uses insertion-order.
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked
list defines the iteration ordering, which is normally the order in
which keys were inserted into the map (insertion-order).
java.util.TreeMap, a SortedMap, uses either natural or custom ordering
of the keys.
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which
constructor is used.