HashTable和HashMap的区别

本文详细对比了HashTable与HashMap的不同之处,包括它们继承的父类、初始数组长度、同步性、对null的支持、hash值计算算法及扩容策略等方面。

 

继承的父类不同:

 * @since JDK1.0
 */
public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {

 

 * @since   1.2
 */

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
{

 

初始数组长度不同:

    /**
     * Constructs a new, empty hashtable with a default initial capacity (11)
     * and load factor (0.75).
     */
    public Hashtable() {
    this(11, 0.75f);
    }
   /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
    }

 

方法时否是同步的:
key是否可以是null:HashMap可以,HashTable不可以
value是不可以是null,HashMap可以,HashTable不可以


   /**
     * Maps the specified <code>key</code> to the specified
     * <code>value</code> in this hashtable. Neither the key nor the
     * value can be <code>null</code>. <p>
     *
     * The value can be retrieved by calling the <code>get</code> method
     * with a key that is equal to the original key.
     *
     * @param      key     the hashtable key
     * @param      value   the value
     * @return     the previous value of the specified key in this hashtable,
     *             or <code>null</code> if it did not have one
     * @exception  NullPointerException  if the key or value is
     *               <code>null</code>
     * @see     Object#equals(Object)
     * @see     #get(Object)
     */
    public synchronized V put(K key, V value) {
    // Make sure the value is not 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;
    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
        V old = e.value;
        e.value = value;
        return old;
        }
    }

    modCount++;
    if (count >= threshold) {
        // Rehash the table if the threshold is exceeded
        rehash();

            tab = table;
            index = (hash & 0x7FFFFFFF) % tab.length;
    }

    // Creates the new entry.
    Entry<K,V> e = tab[index];
    tab[index] = new Entry<K,V>(hash, key, value, e);
    count++;
    return null;
    }
 HashMap:
 /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

 

HashTable:
如果value是null,则会抛NullPointerException

    /**
     * Returns a string representation of this <tt>Hashtable</tt> object
     * in the form of a set of entries, enclosed in braces and separated
     * by the ASCII characters "<tt>,&nbsp;</tt>" (comma and space). Each
     * entry is rendered as the key, an equals sign <tt>=</tt>, and the
     * associated element, where the <tt>toString</tt> method is used to
     * convert the key and element to strings.
     *
     * @return  a string representation of this hashtable
     */
    public synchronized String toString() {
    int max = size() - 1;
    if (max == -1)
        return "{}";

    StringBuilder sb = new StringBuilder();
    Iterator<Map.Entry<K,V>> it = entrySet().iterator();

    sb.append('{');
    for (int i = 0; ; i++) {
        Map.Entry<K,V> e = it.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key.toString());
        sb.append('=');
        sb.append(value == this ? "(this Map)" : value.toString());

        if (i == max)
        return sb.append('}').toString();
        sb.append(", ");
    }
    }

 



put和get时计算hash值的算法不同:
HashTable直接使用了hashCode()方法的值;

HashMap:
  
  public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
HashMap:
    /**
     * Applies a supplemental hash function to a given hashCode, which
     * defends against poor quality hash functions.  This is critical
     * because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

 

HashTable:

    public synchronized V put(K key, V value) {
    // Make sure the value is not 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;

 

 

扩容的大小不同:

HashTable 

 /**
     * Increases the capacity of and internally reorganizes this
     * hashtable, in order to accommodate and access its entries more
     * efficiently.  This method is called automatically when the
     * number of keys in the hashtable exceeds this hashtable's capacity
     * and load factor.
     */
    protected void rehash() {
    int oldCapacity = table.length;
    Entry[] oldMap = table;

    int newCapacity = oldCapacity * 2 + 1;
    Entry[] newMap = new Entry[newCapacity];

    modCount++;
    threshold = (int)(newCapacity * loadFactor);
    table = newMap;

    for (int i = oldCapacity ; i-- > 0 ;) {
        for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
        Entry<K,V> e = old;
        old = old.next;

        int index = (e.hash & 0x7FFFFFFF) % newCapacity;
        e.next = newMap[index];
        newMap[index] = e;
        }
    }
    }

 

HashMap
    /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }

 

http://my.oschina.net/placeholder/blog/180069

http://blog.youkuaiyun.com/chenssy/article/details/22896871 

 

转载于:https://www.cnblogs.com/softidea/p/5487973.html

内容概要:本文系统介绍了算术优化算法(AOA)的基本原理、核心思想及Python实现方法,并通过图像分割的实际案例展示了其应用价值。AOA是一种基于种群的元启发式算法,其核心思想来源于四则运算,利用乘除运算进行全局勘探,加减运算进行局部开发,通过数学优化器加速函数(MOA)数学优化概率(MOP)动态控制搜索过程,在全局探索与局部开发之间实现平衡。文章详细解析了算法的初始化、勘探与开发阶段的更新策略,并提供了完整的Python代码实现,结合Rastrigin函数进行测试验证。进一步地,以Flask框架搭建前后端分离系统,将AOA应用于图像分割任务,展示了其在实际工程中的可行性与高效性。最后,通过收敛速度、寻优精度等指标评估算法性能,并提出自适应参数调整、模型优化并行计算等改进策略。; 适合人群:具备一定Python编程基础优化算法基础知识的高校学生、科研人员及工程技术人员,尤其适合从事人工智能、图像处理、智能优化等领域的从业者;; 使用场景及目标:①理解元启发式算法的设计思想与实现机制;②掌握AOA在函数优化、图像分割等实际问题中的建模与求解方法;③学习如何将优化算法集成到Web系统中实现工程化应用;④为算法性能评估与改进提供实践参考; 阅读建议:建议读者结合代码逐行调试,深入理解算法流程中MOA与MOP的作用机制,尝试在不同测试函数上运行算法以观察性能差异,并可进一步扩展图像分割模块,引入更复杂的预处理或后处理技术以提升分割效果。
### 回答1: HashtableHashMap都是基于哈希表实现的数据结构,它们的主要区别在于线程安全性迭代器的遍历方式。 Hashtable是线程安全的,因为它的所有方法都是同步的,但这也导致了它的性能较差。而HashMap则不是线程安全的,但它的性能更好。 另外,Hashtable的迭代器遍历是通过Enumeration实现的,而HashMap的迭代器遍历是通过Iterator实现的。Enumeration只能读取数据,而Iterator可以同时读取删除数据,因此Iterator更加灵活。 总之,如果需要线程安全的哈希表,可以选择Hashtable;如果需要更好的性能灵活的迭代器遍历方式,可以选择HashMap。 ### 回答2: Hashtable HashMap 都是常用的哈希表数据结构,它们之间的区别如下: 1. 继承关系:Hashtable 是基于 Dictionary 类的一个旧实现,而 HashMap 是继承自 AbstractMap 类的新实现。 2. 线程安全性:Hashtable 是线程安全的,所有的方法都是同步的,而 HashMap 不是线程安全的。在多线程环境下,如果需要线程安全,可以使用 ConcurrentHashMap。 3. Null 值:Hashtable 不允许键或值为 null,否则会抛出 NullPointerException,而 HashMap 可以允许键或值为 null。 4. 性能:由于 Hashtable 是同步的,所以在多线程环境下,访问 Hashtable 的性能相对较低,而 HashMap 不受同步影响,在单线程环境下,访问 HashMap 的性能较高。 5. 迭代器:迭代器遍历 Hashtable 时,是通过 Enumeration 实现的,而 HashMap 的迭代器是通过 Iterator 实现的。 6. 初始容量扩容:Hashtable 的初始容量为 11,扩容时增加原容量的一倍加一;HashMap 的初始容量为 16,扩容时增加原容量的一倍。由于 Hashtable 的初始容量较小,在数据量较大时,扩容的次数较多,可能对性能产生一定影响。 综上所述,HashMapHashtable 的轻量级实现,由于其非线程安全允许 null 值的特性,更适用于单线程环境或需要高性能的场景。而 Hashtable 则适用于多线程环境下需要线程安全性的场景。 ### 回答3: Hashtable HashMap 都是常见的用于存储管理键值对的数据结构,它们的主要区别如下: 1. 继承关系:Hashtable 是 Dictionary 类的子类,而 HashMap 是 AbstractMap 类的子类。这意味着 HashMap 可以单独定义其更丰富的功能,而 Hashtable 只能基于 Dictionary 的功能进行操作。 2. 线程安全性:Hashtable 是线程安全的,内部的方法都使用 synchronized 关键字保证了线程安全性,因此适用于多线程环境。而 HashMap 不是线程安全的,如果在多线程环境下使用 HashMap,需要额外考虑线程同步问题。 3. 允许键值为空:HashMap 允许键值都为空,而 Hashtable 不允许键值为空,否则会抛出 NullPointerException 异常。 4. 性能:由于 Hashtable 是线程安全的,所以在进行读写操作时会有一定的性能开销。而 HashMap 在单线程环境下的性能要高于 Hashtable。 总的来说,如果在单线程环境下使用,且不需要考虑线程同步问题,则推荐使用 HashMap;如果在多线程环境下使用,或需要保证线程安全性,则可以选择使用 Hashtable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值