首页 > 代码库 > HashMap和TreeMap

HashMap和TreeMap

hashMap

HashMap工作原理
我对hashMap的认识基本是对的,hashCode() and equals() is important for hashMap. 除了这个完全不知道

当重新调整HashMap大小的时候,确实存在条件竞争,因为如果两个线程都发现HashMap需要重新调整大小了,它们会同时试着调整大小。在调整大小的过程中,存储在链表中的元素的次序会反过来,因为移动到新的bucket位置的时候,HashMap并不会将元素放在链表的尾部,而是放在头部,这是为了避免尾部遍历(tail traversing)。如果条件竞争发生了,那么就死循环了。这个时候,你可以质问面试官,为什么这么奇怪,要在多线程的环境下使用HashMap呢?:)

TreeMap

TreeMap is base on RB-Tree.

  • 如果键值没有实现java.lang.Comparable是真的不行的。。。

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest‘s Introduction to Algorithms.

HashMap和TreeMap