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关键词

 

posted on 2016-09-01 18:15  悄悄的来,匆匆的走  阅读(211)  评论(0编辑  收藏  举报

导航