问题
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.
回答1:
HashMap :-
HashMapnever preserves your Insertion Order. It Internally Use a hashing Concept by which it generate aHashCodeto the Correspondingkeyand add it to theHashMap.LinkedHashMap :-
LinkedHashMapIt preserves your Insertion Order. andkeyswill be found as same order you Insert into thisLinkedHashMap.TreeMap :- The
TreeMapclass implements theMapinterface by using a Tree. ATreeMapprovides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.
You should note that, unlike a HashMap, a tree map guarantees that its elements will be sorted in ascending key order
回答2:
HashMap has no inherent ordering. If you're looking for insertion order, use a LinkedHashMap. If you're looking for natural order (A-Z, 0-9), use a TreeMap.
回答3:
Use TreeMap for Ascending order.
Syntax:
TreeMap<Integer, Integer> ctrArMap= new TreeMap<Integer, Integer>();
ctrArMap.put( 1, 11);
ctrArMap.put( 3, 12);
ctrArMap.put( 2, 13);
ctrArMap.put( 5, 14);
ctrArMap.put( 4, 15);
System.out.println(ctrArMap);
回答4:
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.
回答5:
The simple answer is no, a hash map doesn't have an "order". It is all determined based on how the object is hashed. For a number you could see some ordering, but that is purely based on the hashCode() method of the object that is the key for the put().
If you can get your hands on the source of the Integer class or similar number classes and look at the hashCode() method you'll probably see why your numbers in the HashMap come back in order. If you switch to a string key you will most likely immediately see that it is no longer sorted.
来源:https://stackoverflow.com/questions/36026761/hashmap-put-is-it-always-ordering