Issue
When we add values to hashmap<Key, Value>
variable using put()
, are they always ordering?
Because when I tried with simple codes they are ordering.
Example:
Map<Integer, Integer> ctrArMap = new HashMap<Integer, Integer>();
ctrArMap.put( 1, 11);
ctrArMap.put( 2, 12);
ctrArMap.put( 3, 13);
ctrArMap.put( 4, 14);
ctrArMap.put( 5, 15);
System.out.println(ctrArMap);
But in my case they aren't ordering.
Solution
HashMap doesn't preserve the order of insertion. However if you use the values 0 to 10 in order, these happen to be hashed to the buckets 0 to 10 internally and placed in an array in that order. When you iterate of the HashMap you are looking at these buckets in order. Note: this implementation could change in the future and this might not happen.
The default size of a HashMap is 16 and with a load factor of 0.7 you can add 11 values without it resizing. This means when you view these values, the current implementation happens to place 0 to 10 in sorted order.
If you only need the values 0 to 10 be in order, I suggest using an array, instead of a HashMap.
Answered By - Peter Lawrey
Answer Checked By - Marie Seifert (JavaFixing Admin)