java HashMap HashSet的存储方式
今天遇到一个bug,简单的说就是把自定义对象作为key 存到HashMap中之后,经过一系列操作(没有remove操作)之后 用该对象到map中取,返回null。
然后查看了HashMap的源代码,get方法的核心代码如下:
final Entry<K,V> getEntry(Object key) {
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;
}
可以看出 hashmap在比较Key的时候,是先比较该key的hashcode. 返回entry条件是hashcode相同并且对象的地址或者equals方法比较相同。然后检查了出现bug的代码,因为重写了hashcode方法,然后修改了对象的属性(与hashcode计算相关)导致不太容易注意到的bug
验证HashMap的存储与hashCode,equals相关:
public class MapTest {
public static void main(String[] args){
People people = new People();
people.age = 1;
people.name = "test";
Map<People,Integer> map = new HashMap<People, Integer>();
map.put(people, 1);
people.age = 2;
System.out.println("同一对象修改hashcode:" + map.get(people));
People otherPeople = new People();
otherPeople.age = 1;
otherPeople.name = "test";
System.out.println("不同对象有相同的hashcode与equals:" + map.get(otherPeople));
} static class People{
public int age;
public String name;
@Override
public int hashCode() {
return age;
} @Override
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof People)){
return false;
} if(((People)obj).name != name){
return false;
}
return true;
}
}
}
结果:
同一对象修改hashcode:null
不同对象有相同的hashcode与equals:1
然后考虑到HashSet是不是也有这样的特性: 因为set是一个不包含相同元素的collections,所以在判断set中是否含有同一个元素的时候,是不是也是根据hashcode跟equals来判断的,Set源码的add方法如下:
private transient HashMap<E,Object> map; public HashSet() {
map = new HashMap<>();
} public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
可以看出HashSet的add实际上使用HashMap来实现的,所以用的是同一个机制:判断是否包含某个对象,1.首先hashcode相同,2.然后地址或者equals方法比较相同,条件1跟2是&&关系,而不是||关系
这是hashmap/hashset的判断是否包含某个key或者元素的机制,然后看看其他map接口的实现类,比如ConcurrentSkipListMap:
concurrentSkipListMap#put方法核心代码:
Node<K,V> b = findPredecessor(key);
Node<K,V> n = b.next;
for (;;) {
if (n == null)
return null;
Node<K,V> f = n.next;
if (n != b.next) // inconsistent read
break;
Object v = n.value;
if (v == null) { // n is deleted
n.helpDelete(b, f);
break;
}
if (v == n || b.value == null) // b is deleted
break;
int c = key.compareTo(n.key);
if (c == 0)
return n;
if (c < 0)
return null;
b = n;
n = f;
}
}
以上代码第16行可看出:比较的时候是根据对象重写的compareTo方法来比较的,我们做个测试:
public class MapTest {
public static void main(String[] args){
People people = new People();
people.age = 1;
people.name = "test";
Map<People,Integer> map = new ConcurrentSkipListMap<People, Integer>();
map.put(people, 1);
people.age = 2;
System.out.println(map.get(people));
People otherPeople = new People();
otherPeople.age = 1;
otherPeople.name = "test1";
System.out.println(people.compareTo(people));
System.out.println(people.compareTo(otherPeople));
System.out.println(map.get(otherPeople));
} static class People implements Comparable{
public int age;
public String name; @Override
public int compareTo(Object o) {
if(o == null || !(o instanceof People)){
return -1;
}
return ((People)o).age == age?0:-1;
}
}
}
结果:
1
0
-1
null
分析:hashmap比较hash值,而在map put进对象的时候 该hash值就已经固定了(详情参考HashMap内部类Entry<K,V>),所以put进之后如果改变与hashcode方法的计算有关系的属性时,hashcode()返回的变了,map里也就找不到了
而concurrentSkipListMap比较的是对象的compartTo()方法(concurrentSkipListMap的key必须实现Comparable接口),同一个对象,不管改变什么属性,改变之后自己跟自己compareTo返回的肯定是相等的,因为比较的都是改变之后的同一个对象,而不像hashmap一样,是执行put方法的时候获取的hashcode值与改变之后的值相比较。所以concurrentSkipListMap的key不管属性怎么变 get(对象本身)都能获取到。上段代码,最后一个返回null的原因是:因为people的age已经变成了2,也就是说concurrentSkipListMap中的该对象(key)的age也是2,而otherpeople的age是1, compareto()方法返回不是零。所以get的时候返回null。
java HashMap HashSet的存储方式的更多相关文章
- 原码,补码,反码的概念及Java中使用那种存储方式
原码,补码,反码的概念及Java中使用那种存储方式: 原码:原码表示法是机器数的一种简单的表示法.其符号位用0表示正号,用:表示负号,数值一般用二进制形式表示 补码:机器数的补码可由原码得到.如果机器 ...
- Java HashMap两种遍历方式
第一种: Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Ma ...
- Java HashMap 四种遍历方式
HashMap遍历方式包含以下4种: 1.遍历KeySet,再通过Key来getValue. 2.使用entrySet的迭代器. 3.foreach entrySet的方式. 3.foreache v ...
- Java集合 -- HashSet 和 HashMap
HashSet 集合 HashMap 集合 HashSet集合 1.1 Set 接口的特点 Set体系的集合: A:存入集合的顺序和取出集合的顺序不一致 B:没有索引 C:存入集合的元素没有重复 1. ...
- Java中HashSet和HashMap
Set中存储元素为什么不重复(即使hashCode相同)? HashSet中存放自定义类型元素时候,需要重写对象中的hashCode方法和equals方法, HashSet中存放自定义类型元素时候,需 ...
- Java 集合 HashMap & HashSet 拾遗
Java 集合 HashMap & HashSet 拾遗 @author ixenos 摘要:HashMap内部结构分析 Java HashMap采用的是冲突链表方式 从上图容易看出,如果选择 ...
- Java List/HashSet/HashMap的排序
在对Java无序类集合,如List(ArrayList/LinkedList).HashSet(TreeSet有序).HashMap等排序时,Java中一个公共的类Collections,提供了对Ja ...
- Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式)
Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式) 原文地址:http://alanland.iteye.com/admin/blogs/1600685(欢迎转载 ...
- StoreType.java 存储方式
StoreType.java 存储方式 http://injavawetrust.iteye.com package com.iteye.injavawetrust.miner; /** * 存储方式 ...
随机推荐
- 自动化构建工具gulp的基础了解
1.使用gulp的步骤 1.安装node检测是否安装好 cmd->node -v2.安装gulp 可以在npm或者在cnpm3.在node里面有个文件package.json.利用命令行npm ...
- [转]iOS开发总结之代码规范
转自:http://www.cocoachina.com/ios/20151014/13678.html 命名规范 总 的来说, iOS命名两大原则是:可读性高和防止命名冲突(通过加前缀来保证). O ...
- linux 命令——56 netstat(转)
netstat命令用于显示与IP.TCP.UDP和ICMP协议相关的统计数据,一般用于检验本机各端口的网络连接情况.netstat是在内核中访问网络及相关信息的程序,它能提供TCP连接,TCP和UDP ...
- html body上有一条空白!!!
html body 上莫名其妙的就出现了一条空白,怎么搞都搞不定,弄了一下午...... 解决了!!! 格式问题/
- window.onload中调用函数报错的问题
今天练习js,忽然遇到了一个问题,就是window.onload加载完成后,调用其中的函数会报错, 上一段简单的代码: 报错信息: 报错原因: 当window.onload加载完成后,第一个alert ...
- 报 "错误: 无法取消引用int" 的问题解决纪录
很久没上博客园了,估计有一年左右了,最近在写一个android的小工具应用,今天写多国语言时,引用 string.xml里面的值,R.string.XXX时,突然报 『错误: 无法取消引用int』,我 ...
- CUDA:Supercomputing for the Masses (用于大量数据的超级计算)-第七节
第七节:使用下一代CUDA硬件,快乐加速度 原文链接 Rob Farber 是西北太平洋国家实验室(Pacific Northwest National Laboratory)的高级科研人员.他在多个 ...
- nginx安装与部署
1:安装工具包 wget.vim和gcc yum install -y wget yum install -y vim-enhanced yum install -y make cmake gcc g ...
- 安装并配置多实例Mysql数据库
1.安装Mysql需要的依赖包 yum -y install ncurses-devel libaio-devel cmake 2.创建Mysql用户账号 useradd -s /sbin/nolog ...
- JZOJ 3493. 【NOIP2013模拟联考13】三角形
3493. [NOIP2013模拟联考13]三角形(triangle) (File IO): input:triangle.in output:triangle.out Time Limits: 10 ...