Hashmap put(), is it always ordering?

限于喜欢 提交于 2019-12-22 09:21:50

问题


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:


  1. HashMap :- HashMap never preserves your Insertion Order. It Internally Use a hashing Concept by which it generate a HashCode to the Corresponding key and add it to the HashMap.

  2. LinkedHashMap :- LinkedHashMap It preserves your Insertion Order. and keys will be found as same order you Insert into this LinkedHashMap.

  3. TreeMap :- The TreeMap class implements the Map interface by using a Tree. A TreeMap provides 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!