温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

分析JDK的HashMap的原理

发布时间:2021-11-03 17:44:43 来源:亿速云 阅读:129 作者:iii 栏目:编程语言

这篇文章主要介绍“分析JDK的HashMap的原理”,在日常操作中,相信很多人在分析JDK的HashMap的原理问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”分析JDK的HashMap的原理”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1. 特性

我们可以用任何类作为HashMap的key,但是对于这些类应该有什么限制条件呢?且看下面的代码:

public class Person {     private String name;     public Person(String name) {         this.name = name;     } } MaptestMap = new HashMap<>(); testMap.put(new Person("hello"), "world"); testMap.get(new Person("hello")); // ---> null

本是想取出具有相等字段值Person类的value,结果却是null。对HashMap稍有了解的人看出来——Person类并没有override hashcode方法,导致其继承的是Object的hashcode(返回是其内存地址),两次new出来的Person对象并不equals——这也是为什么在工程项目中常用不变类(如String、Integer等)做为HashMap的key的原因。那么,HashMap是如何利用hashcode给key做索引的呢?

2. 原理

首先,我们来看《Thinking in Java》中一个简单HashMap的实现方案:

//: containers/SimpleHashMap.java // A demonstration hashed Map. import java.util.*; import net.mindview.util.*; public class SimpleHashMapextends AbstractMap{   // Choose a prime number for the hash table size, to achieve a uniform distribution:   static final int SIZE = 997;   // You can't have a physical array of generics, but you can upcast to one:   @SuppressWarnings("unchecked")   LinkedList<1mapentry>[] buckets =     new LinkedList[SIZE];   public V put(K key, V value) {     V oldValue = null;     int index = Math.abs(key.hashCode()) % SIZE;     if(buckets[index] == null)       buckets[index] = new LinkedList<1mapentry>();     LinkedList<1mapentry> bucket = buckets[index];     MapEntrypair = new MapEntry(key, value);     boolean found = false;     ListIterator<1mapentry> it = bucket.listIterator();     while(it.hasNext()) {       MapEntryiPair = it.next();       if(iPair.getKey().equals(key)) {         oldValue = iPair.getValue();         it.set(pair); // Replace old with new         found = true;         break;       }     }     if(!found)       buckets[index].add(pair);     return oldValue;   }   public V get(Object key) {     int index = Math.abs(key.hashCode()) % SIZE;     if(buckets[index] == null) return null;     for(MapEntryiPair : buckets[index])       if(iPair.getKey().equals(key))         return iPair.getValue();     return null;   }   public Set<1map.entry> entrySet() {     Set<1map.entry> set= new HashSet<1map.entry>();     for(LinkedList<1mapentry> bucket : buckets) {       if(bucket == null) continue;       for(MapEntrympair : bucket)         set.add(mpair);     }     return set;   }   public static void main(String[] args) {     SimpleHashMapm =       new SimpleHashMap();     m.putAll(Countries.capitals(25));     System.out.println(m);     System.out.println(m.get("ERITREA"));     System.out.println(m.entrySet());   } }

SimpleHashMap构造一个hash表来存储key,hash函数是取模运算Math.abs(key.hashCode()) % SIZE,采用链表法解决hash冲突;buckets的每一个槽位对应存放具有相同(hash后)index值的Map.Entry,如下图所示:
分析JDK的HashMap的原理
JDK的HashMap的实现原理与之相类似,其采用链地址的hash表table存储Map.Entry:

/**  * The table, resized as necessary. Length MUST Always be a power of two.  */ transient Entry[] table = (Entry[]) EMPTY_TABLE; static class Entryimplements Map.Entry{     final K key;     V value;     Entrynext;     int hash;     … }

Map.Entry的index是对key的hashcode进行hash后所得。当要get key对应的value时,则对key计算其index,然后在table中取出Map.Entry即可得到,具体参看代码:

public V get(Object key) {     if (key == null)         return getForNullKey();     Entryentry = getEntry(key);     return null == entry ? null : entry.getValue(); } final EntrygetEntry(Object key) {     if (size == 0) {         return null;     }     int hash = (key == null) ? 0 : hash(key);     for (Entrye = 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; }

可见,hashcode直接影响HashMap的hash函数的效率——好的hashcode会极大减少hash冲突,提高查询性能。同时,这也解释开篇提出的两个问题:如果自定义的类做HashMap的key,则hashcode的计算应涵盖构造函数的所有字段,否则有可能得到null。

到此,关于“分析JDK的HashMap的原理”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI