前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HashMap的数据结构(浅谈有与无)

HashMap的数据结构(浅谈有与无)

作者头像
全栈程序员站长
发布2022-07-25 21:39:42
1610
发布2022-07-25 21:39:42
举报

大家好,又见面了,我是你们的朋友全栈君。

HashMap数据结构浅谈

开篇语:hashmap作为一种非常重要的数据结构,无论是在理论学习中,还是实际开发中都会经常遇到。这里总结一下对于hashmap一些基础的知识点。

1、常见的数据结构

一般开发中常见的数据结构有数组、链表、树、及HashMap。

数组结构和链表结构的图形结构非常简单。本次主要讲解HashMap的结构,并结合着源码进行简要分析

2、HashMap

HashMap的结构图如下:

HashMap的数据结构(浅谈有与无)
HashMap的数据结构(浅谈有与无)

主要分为横向的数组和纵向的链表;数组保存的内存中的物理地址,对象的存放索引,纵向的链表保存的是对象的值。

首先看下hashmap的源码,理解下hash存储的过程:

代码语言:javascript
复制
public V put(K key, V value) {
    //hash方法是把一个对象散列成一个int值
	return putVal(hash(key), key, value, false, true);
}



//这里为了更好的阐述,我假定数组的长度为16,key经过散列后的值为9
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    //Node为定义的一个链表结构
	Node<K,V>[] tab; 
	Node<K,V> p; 
	int n, i;
    //下面这个if这样写会更容易理解
	/*
	if (table == null || table.length ==0)
		table = resize();
	tab = table;
	n = tab.length;
	*/
	if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
	//下面这个if表示的是看tab[9]是否为空,可以这样写
	/*
		i = 15 & hash; // 1111 & 1001
		p = tab[9];
		if (p == null) {
			直接把该值放在此地址位上
		}else {
			如果该地址位已经有值了,
			就以链表的方式存放该Entry
		}
	*/
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

可以简要概括了,存放hashmap主要分为两步:

  • 把key进行hash计算得到数组中的索引
  • 把entry值存放到该位置,如果该位置没有值,则直接存放,如果有值则以链表的形式存放

那么现在可以理解为什么采用这种结构,主要解决的是散列冲突问题。

何为散列冲突,即两个或者以上的key经过hash函数计算之后得到同一个值。

3、注重点

因此到这里,我们可以从原理上理解如果重写Object的equals 方法的时候,也同时需要复写hashcode()。 例如下面的测试,

代码语言:javascript
复制
@Data
@AllArgsConstructor
class Student {
    private String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;
        return this.name == student.getName();
    }

}
public class Test {
    public static void main(String[] args) {
        Student student1 = new Student("zhangsan");
        Student student2 = new Student("zhangsan");
        System.out.println(student1.equals(student2));//true
        Map<Student,String> map = new HashMap<>();
        map.put(student1,"上海大学");

        System.out.println(map.get(student2));//null

    }
}

系统分析: 首先key值虽然重写了equals方法,使他们逻辑上相等。但是在map存放的时候需要hash(Student),而每个student的hashcode是不一样的。看如下源码。因此,我们犯了刻舟求剑同样的错误。

代码语言:javascript
复制
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

4、总结

本文只是对hashmap进行一个简要的分析,由于能力有限,水平一般,不正之处敬请指正。每篇博文都是作者学习之路的一篇结晶。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127894.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022年4月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • HashMap数据结构浅谈
    • 1、常见的数据结构
      • 2、HashMap
        • 3、注重点
          • 4、总结
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档