前几天线上异常监控检测到一个NullPointerException,于是根据异常栈提示定位到具体发生异常的代码,这里记录下出现异常的原因。先来段简单的代码复现问题。
public class TestObject{
private Integer status;
public TestObject(Integer status){
this.status = status;
}
public static void main(String[] args){
Map<TestObject, Integer> map = new HashMap<TestObject, Integer>();
TestObject object = new TestObject(1);
map.put(object, 1);
// System.out.println(object.hashCode());
System.out.println(map.get(object));
object.setstatus(2);
// System.out.println(object.hashCode());
System.out.println(map.get(object));
}
}
上面这端代码会打印两段内容
1
null
因为我们修改了map中的key,虽然对象还是那个对象,但是大家可以把上面注释的代码放开去看下两次打印的hashCode是不是发生了改变。我们知道map在存放数据时是需要借助key的hash值去决定value的存放位置,因此一旦key的hash值发生了变化,就无法找到对应的value。
要解决这个bug有两种方法
1.修改map的数据结构
2.重写key的hashCode方法,使得即使对象属性发生变化时,hash值一直不变