zoukankan      html  css  js  c++  java
  • hashMap和hashTable的区别

    相同点:

    1.都是无序的

    不同点:

    1.HashMap 可以放null ,HashTable 不可以

    2.HashTable 是线程安全的,HashMap不是线程安全的,需要手动同步,

     Map m = Collections.synchronizedMap(new HashMap());
          ...
      Set s = m.keySet();  // Needn't be in synchronized block
          ...
      synchronized(m) {  // Synchronizing on m, not s!
          Iterator i = s.iterator(); // Must be in synchronized block
          while (i.hasNext())
              foo(i.next());
      }

    HashTable 部分源码:

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

    HashMap部分源码:

    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;
        }

    无synchronized关键词

  • 相关阅读:
    Yii AR Model 查询
    学习进度4
    学习进度三
    个人每日总结7
    个人每日总结6
    个人每日总结5
    个人每日总结4
    个人冲刺承担的任务项目的用户模板和用户场景模板
    个人每日总结3
    个人每日总结2
  • 原文地址:https://www.cnblogs.com/fuyuanming/p/5830883.html
Copyright © 2011-2022 走看看