• 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);
            }
  • 相关阅读:
    如何制作动态层分组报表
    填报表之数据留痕
    填报表中也可以添加 html 事件
    填报脚本之轻松搞定复杂表的数据入库
    在报表中录入数据时如何实现行列转换
    如何在报表中绘制 SVG 统计图
    如何用报表工具实现树状层级结构的填报表
    6.JAVA_SE复习(集合)
    JAVA_SE复习(多线程)
    数据库基本概念
  • 原文地址:https://www.cnblogs.com/YYfish/p/6629648.html
Copyright © 2020-2023  润新知