According to these:
- http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
- Difference between HashMap, LinkedHashMap and TreeMap
- java beginner : How key gets sorted in hashmaps?
The HashMap
in Java
should be unsorted but it is being sorted with respect to Key
.
I experienced this as a problem because I needed inserted-order data. So, I used LinkedHashMap
instead. But still I am confused why the HashMap
sorted it.
Can anyone explain it?
I did a simple example to view the sort.
public static void main(String[] args) {
HashMap<Integer, String> newHashMap = new HashMap<Integer, String>();
newHashMap.put(2, "First");
newHashMap.put(0, "Second");
newHashMap.put(3, "Third");
newHashMap.put(1, "Fourth");
Iterator<Entry<Integer, String>> iterator = newHashMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey());
System.out.println("Value: " + entry.getValue());
iterator.remove();
}
}
Result:
Key: 0
Value: Second
Key: 1
Value: Fourth
Key: 2
Value: First
Key: 3
Value: Third
Edit:
I tried to insert 50 random numbers using Random
of Java
and I found some data unsorted. But, it still manages to sort most of the integers.
Random results:
...
Key: 36
Value: random
Key: 43
Value: random
Key: 47
Value: random
Key: 44
Value: random
Key: 45
Value: random
...