zoukankan      html  css  js  c++  java
  • HashMap 初步探究

    HashMap 是开发过程中,非常常用的一个类, 常常会被拿来与HashTable比较,什么什么鬼之类的。

    HashMap与HashTable之间的区别:

    1..HashMap允许Key Value 为null, HashTable 不可以

    2..HashMap 非线程安全性, HashTable 是线程安全。 (HashTable 的方法有synchronized 同步锁, 而HashMap没有)

    3..线程安全性就会影响速度的快慢, HashMap比HashTable快。

    4..HashMap使用的是Iterator迭代器(fail-fast), 而HashTable 用的是enumerator. (iterator接口比enumerator多了一个remove,所以在多个线程对一个集合进行操作时,有可能会抛出ConcurrentModificationException异常【fail-fast】)

    比较完之后,学习一下HashMap的源码

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

    首先,HashMap继承了AbstractMap抽象类, 以及实现了Map,Cloneable,Serializable三个接口。

      public V get(Object key) {
            Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }

    看看HashMap中的get方法, 可以看到, 里面关键的方法就是getNode(hash(key),key)的方法

    final Node<K,V> getNode(int hash, Object key) {
            Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
            if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {
          //hash & (length-1)得到对象的保存位
    if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first;
          //检查第一个是否符合,是则返回
    if ((e = first.next) != null) { if (first instanceof TreeNode) 
        // 如果first 为TreeNode (红黑树)
        //当链表长度超过8的时候将数组里面的链表转化成为红黑树
    return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                  //与第一次检查条件一样,直至找到符合的e, 或者e.next==null跳出.
    return e; } while ((e = e.next) != null); } } return null; }
     final TreeNode<K,V> getTreeNode(int h, Object k) {
                return ((parent != null) ? root() : this).find(h, k, null);
            }
  • 相关阅读:
    010:请教STM32用JLINK V8 SWD输出调试信息到ITM Viewer的问题(转)
    014:针对mdk中STM32程序无法使用printf,产生停留BEAB BKPT 0xAB处问题的解决(转)
    011:Nuvoton(新唐) Cortex M0 使用semihost输入输出办法(转)
    015:6步教你在STM32程序中添加 printf函数(转)
    js定时和离开当前页面事件 明天
    linux常用命令 明天
    mongoDB常用命令 明天
    自定义标签的使用 明天
    浏览器事件 明天
    SonarQube简介
  • 原文地址:https://www.cnblogs.com/YYfish/p/6629648.html
Copyright © 2011-2022 走看看