java 数据结构之HashTable

本文深入探讨了Java中HashTable类的特点与应用,对比HashMap与ConcurrentHashMap,解析其线程安全机制及迭代器实现,适合Java开发者深入了解集合框架。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                                           java 数据结构之HashTable

HashTable是一个比较早的类,也是一个数组链表的数据结构,跟HashMap特别像,都实现了Map接口,但是HashTable只允许non-null的key或者value,另外HashTable是线程安全的,可以看到HashTable的方法使用了synchronized关键字来修饰,所以是线程安全的,synchronized这个关键字是以后结合java其他的同步技术来说下。

 * Java Collections Framework</a>.  Unlike the new collection
 * implementations, {@code Hashtable} is synchronized.  If a
 * thread-safe implementation is not needed, it is recommended to use
 * {@link HashMap} in place of {@code Hashtable}.  If a thread-safe
 * highly-concurrent implementation is desired, then it is recommended
 * to use {@link java.util.concurrent.ConcurrentHashMap} in place of
 * {@code Hashtable}.

简单来说如果不需要线程安全,推荐使用hashMap,效率更高,如果需要使用线程安全,就使用ConcurrentHashMap类,这么说起来其实HashTable有点鸡肋。

另外,HashMap与HashTable还有一个区别就是迭代器的不同,具体看下,先看HashMap的迭代器

    private abstract class HashIterator<E> implements Iterator<E> {
        Entry<K,V> next;        // next entry to return
        int expectedModCount;   // For fast-fail
        int index;              // current slot
        Entry<K,V> current;     // current entry

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)//当hashMap的结构被修改时候,抛出异常,fail-fast
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Object k = current.key;
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
    }

可以看到,当hashMap的结构发生改变,也就是迭代HashMa元素时调用put或者remove方法,会抛出ConcurrentModificationException异常。但是你可以使用迭代器的remove方法来移除对象。

HashTable中的迭代器是Enumerator,具体可以看代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值