HashMap源码解析(jdk1.7)

news/2024/7/4 3:47:19

HashMap源码解析

  • 初始化信息
  • 添加元素
  • 删除元素
  • 查找元素
  • containsKey:指定的key是否在HashMap中
  • containsValue:查找HashMap中是否有指定的value
  • isEmpty
  • indexFor:返回h在table数组中的位置
  • 写在后面

初始化信息

 	//HashMap的初始容量,必须是2的n次幂
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 

    //HashMap的最大容量,必须是2的n次幂
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //存储数据的Entry数组,每一个entry是一个链表
    static final Entry<?,?>[] EMPTY_TABLE = {};

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     * 这个entry数组,随着需要改变大小,长度必须是2的n次幂
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    //HashMap中元素的总个数
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * HashMap的阈值,用于判断是否需要调整HashMap的大小,threshold = capacity * load factor
     * 初始大小 = 16 * 0.75 = 12
     */
    // If table == EMPTY_TABLE then this is the initial capacity at which the
    // table will be created when inflated.
    int threshold;

    //加载因子实际大小
    final float loadFactor;

    //HashMap被改变的次数
    transient int modCount;

    //HashMap的默认阈值
    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

添加元素

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
  		
        if (key == null)//如果key为null,则将此value放到table[0]中的链表上
            return putForNullKey(value);
        int hash = hash(key);
        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);//如果没有重复的key,将当前元素放到table[i]的桶上
        return null;
    }

 private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

 void addEntry(int hash, K key, V value, int bucketIndex) {
   /**
    * 判断当前的数组大小和阈值的关系,如果当前阈值≤数组大小且table[bucketIndex]不为null,
    * 就扩容,然后重新计算当前元素的位置
    */
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);//重新计算桶的位置,因为桶的位置和桶的长度有关
        }

        createEntry(hash, key, value, bucketIndex);
    }


 void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];//先保存table[bucketIndex]的元素到e
        table[bucketIndex] = new Entry<>(hash, key, value, e);//然后将e设置为新元素的下一个节点,新元素为该链表的头结点
        size++;
   
   
   //entry的构造方法如下
   Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
    }
   
 }


 void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        transfer(newTable, initHashSeedAsNeeded(newCapacity));//将元素从移动到newTable中
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);//重新调整阈值
  }

   /**
     * Transfers all entries from current table to newTable.
     */
    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

删除元素

public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
}

final Entry<K,V> removeEntryForKey(Object key) {
        if (size == 0) {//如果没有元素,返回null
            return null;
        }
        int hash = (key == null) ? 0 : hash(key);
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            //查找到元素,删除单链表的节点
            //只需将当前元素的前一个节点的下一个节点指向下下一个节点即可,即prev.next = next.next
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)//如果相等,表示删除的是第一个元素,所以要把table[i]指向next
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }
        return e;//如果这个桶没有元素,返回null
    }

查找元素

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);
        return null == entry ? null : entry.getValue();
    }

   final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

containsKey:指定的key是否在HashMap中

 public boolean containsKey(Object key) {
        return getEntry(key) != null;
  }

    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

containsValue:查找HashMap中是否有指定的value

    public boolean containsValue(Object value) {
        if (value == null)
            return containsNullValue();

        Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (value.equals(e.value))
                    return true;
        return false;
    }

private boolean containsNullValue() {
        Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (e.value == null)
                    return true;
        return false;
    }

isEmpty

 public boolean isEmpty() {
        return size == 0;
 }

indexFor:返回h在table数组中的位置

/**
 * Returns index for hash code h.这里用&运算代替了取模运算,加快了速度,因为HashMap中的长度都是按照2的幂增长的,所以,length - 1 换算成二进制就是1111111。。。;所以h&(length-1)和h%length在数值上时一致的,但是速度更快。
 */
static int indexFor(int h, int length) {
  return h & (length-1);
}

写在后面

异或运算(^)

//异或运算,转换为二进制,相同为0,不同为1
System.out.println(1^1);//0
System.out.println(1^0);//1

三目运算符

//三目运算符从左往右运算
int i = 1 > 0 ? 2 : 3 > 0 ? 7 : 8;
int j = 1 < 0 ? 2 : 3 > 0 ? 7 : 8;

System.out.println(i);//2
System.out.println(j);//7

hashcode值

同一个对象的hash值一定相同,同一个字符串的hash值一定相同;反之不一定。

两个对象相等,则hash值一定相同;反之不一定。


http://www.niftyadmin.cn/n/1995595.html

相关文章

ZwQueryInformationFile 函数

ZwQueryInformationFile 函数The ZwQueryInformationFile routine returns various kinds of information about a given file object. NTSTATUS ZwQueryInformationFile( IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformatio…

Tapestry在静态页面和动态内容分工方面的研究

Tapestry在静态页面和动态内容分工方面的研究 Tapestry的一个最耀眼的功能是其绝好的模板设计思想&#xff0c;它能够将动态内容以极少的侵入性而展现到HTML页面上&#xff0c;我对其这一功能非常赞赏&#xff0c;如果 Tapestry能够像Spring那样把这一部分HTML模板解析功能独立…

java树形菜单制作

java树形菜单制作用到的技术代码实现用到的技术 SpringMVCSpringmybatiseasyui 代码实现 dto&#xff08;适用于easyui的实体类&#xff09; package com.grand.orgn.dto;import java.util.HashMap; import java.util.Map;/*** * author * 适用于easyUI树形结构的实体类* d…

文件-进程关联演示程序(出自CVC)

文件-进程关联演示程序(出自CVC)1、首先使用ZwQuerySystemInformation查询所有进程句柄&#xff0c;2、获取句柄所代表对象信息&#xff0c;查出目标文件。核心态程序相对简单&#xff0c;对于用户态程序&#xff0c;使用ZwQueryInformationFile同时与GetFileInformationByHand…

Tapestry中配置文件page的简化处理

Tapestry中配置文件page的简化处理 Tapestry每个页面基本上都需要一个.page的配置文件&#xff0c;因为需要对模板HTML的动态内容部分进行配置&#xff0c;这是为静态页面和动态内容更好的分工&#xff0c;确实需要这么做。但是&#xff0c;每个page文件的典型配置如下&#x…

关于由HANDLE获取文件名的问题

问题&#xff1a;关于由HANDLE获取文件名的问题 PFILE_NAME_INFORMATION pfni; pfni(PFILE_NAME_INFORMATION)ExAllocatePool(PagedPool, sizeof(FILE_NAME_INFORMATION) 255 * sizeof(WCHAR) ); memset(pfni,0,sizeof(FILE_NAME_INFORMATION) …

AngularJS controller调用factory

1、定义 factory.js 文件 var appFactorys angular.module(starter.factorys, []) appFactorys.factory(HouseFactory, function () {var houseList [{ id: 0, title: 急售北二环 小区配套齐全 精装修, price: 88.0, describe: 2室1厅 120平米, img: img/ben.png },{ id: 1, …

Tapestry中Sumbit/ImageSubmit的属性selected和tag

Tapestry中Sumbit/ImageSubmit的属性selected和tag 个人认为Submit/ImageSubmit标准组件的两个属性selected和tag的设置比较罗嗦&#xff0c;可能是性能和灵活性的一种权衡吧。其中&#xff0c;selected指定页面类的一个属性&#xff0c;tag设置该页面属性的值。selected和tag…