zoukankan      html  css  js  c++  java
  • HashMap、HashTable

    http://www.cnblogs.com/xinzhao/p/5644175.html

    附上同行写的博客,写的很好

    平常还是要多看源码

    这两个双列集合有什么不同呢?

    做个总结:

    1.HashTable产生于JDK 1.1,而HashMap产生于JDK 1.2。HashMap要比HashTable出现得晚一些

    2.贴源码

    HashTable:

     1     public synchronized V put(K key, V value) {//线程安全的
     2         // Make sure the value is not null
     3         if (value == null) {
     4             throw new NullPointerException();
     5         }
     6 
     7         // Makes sure the key is not already in the hashtable.
     8         Entry<?,?> tab[] = table;
     9         int hash = key.hashCode();//key为null,会抛出空指针异常
    10         int index = (hash & 0x7FFFFFFF) % tab.length;
    11         @SuppressWarnings("unchecked")
    12         Entry<K,V> entry = (Entry<K,V>)tab[index];
    13         for(; entry != null ; entry = entry.next) {
    14             if ((entry.hash == hash) && entry.key.equals(key)) {
    15                 V old = entry.value;
    16                 entry.value = value;
    17                 return old;
    18             }
    19         }
    20 
    21         addEntry(hash, key, value, index);
    22         return null;
    23     }

    HashMap:

    1     public V put(K key, V value) {
    2         return putVal(hash(key), key, value, false, true);
    3     }
    1     static final int hash(Object key) {
    2         int h;
    3         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//key可以为null
    4     }

    HashTable:不能存null键和null值,线程是安全的

    HashMap:可以存null键和null值,线程是不安全的

    HashTable已经被淘汰了,不要在代码中使用

    看看作者怎么说的:

    If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use java.util.concurrent.ConcurrentHashMap in place of Hashtable.

    翻译:就是不需要线程安全的时候使用HashMap,需要线程安全的时候使用ConcurrentHashMap,HashTable已经被淘汰了

  • 相关阅读:
    WebSocket
    Redis
    Memcached
    Python实现支付宝在线支付
    RabbitMQ
    linux内核优化
    kafka资源
    推荐相关
    机器学习好网站
    逻辑回归(logistic regression)的本质——极大似然估计
  • 原文地址:https://www.cnblogs.com/jaro/p/9014434.html
Copyright © 2011-2022 走看看