How does Java order items in a HashMap or a HashTable?

前端 未结 7 1483
星月不相逢
星月不相逢 2020-11-27 14:31

I was wondering how Java orders items in the Map (HashMap or Hashtable) when they are added. Are the keys ordered by the hashcode, mem

7条回答
  •  旧时难觅i
    2020-11-27 14:46

    A Map is not an ordered data structure - you should not rely on entries in a HashMap being in a certain order. Some Map implementations such as LinkedHashMap and TreeMap do guarantee a certain order, but HashMap does not.

    If you really want to know what happens internally, lookup the source code of HashMap - you can find it in src.zip which should be in your JDK installation directory.

    A HashMap has a number of "buckets" in which it stores its entries. Which bucket an entry is stored in is determined by the hash code of the key of the entry. The order in which you see the entries in the HashMap depends on the hash codes of the keys. But don't write programs that rely on entries being in a certain order in a HashMap - the implementation might change in a future version of Java and your program then would not work anymore.

提交回复
热议问题