Hashtable,HashMap,TreeMap的区别

Hashtable

Hashtable是java集合类库早期的一个实现(类名Hashtable不是HashTable),线程同步,不支持null键和值,由于同步,性能较差。

	//synchronized同步
    public synchronized V put(K key, V value) {
       // Make sure the value is not null
       //值不能为null
       if (value == null) {
           throw new NullPointerException();
       }

       // Makes sure the key is not already in the hashtable.
       Entry<?,?> tab[] = table;
       int hash = key.hashCode();
       int index = (hash & 0x7FFFFFFF) % tab.length;
       @SuppressWarnings("unchecked")
       Entry<K,V> entry = (Entry<K,V>)tab[index];
       //值不能为null
       for(; entry != null ; entry = entry.next) {
           if ((entry.hash == hash) && entry.key.equals(key)) {
               V old = entry.value;
               entry.value = value;
               return old;
           }
       }

       addEntry(hash, key, value, index);
       return null;
   

HashMap

HashMap是最常用的集合类之一,底层实现由数据和链表构成。
HashMap线程不同步,可支持null键和值。
HashMap默认容量为16,且要求容量一定为2的整数次幂,当元素增长到需扩容时,默认增加长度一倍
数据中存储的是桶(bucket)后面跟着存储键值对的链表,HashMap通过计算需存储元素的哈希值,决定该元素存储在数据的哪个位置上。相同哈希值的键值对会存在数据的同一个位置上,按链表形式存储。
当相同哈希值的元素个数超过设定的阈值(TREEIFY_THRESHOLD,默认为8)时,则会由链表自动转成红黑
树形式存储。

存储格式:
在这里插入图片描述

TreeMap

TreeMap是一种有序的,基于红黑树实现的Map。常用的put,get,remove时间复杂度O(log(n)),操作速度较慢。元素排序方式,由其成员变量comparator决定:

    /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *
     * @serial
     */
    private final Comparator<? super K> comparator;

可以在TreeMap初始化时,传入自定义的Comparator,以满足自己的排序需要。

  public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }
发布了79 篇原创文章 · 获赞 3 · 访问量 5235

猜你喜欢

转载自blog.csdn.net/SW_LCC/article/details/103847314