手头上边的事情做完了,在看源码的时候想到了以前留的一个坑,就是String源码比较有意思的地
方,想了半天没想起来自己当时是怎么想的,看到了equals方法,决定看看以前老生常谈的一个问题,
为什么重写equals方法要重写hashcode方法
为了搞清这个问题,我自己写了一个测试类
1 | package top.shownmmp.quartz; |
运行上面的代码输出是
1 | equals:true |
问题就出现了
先看object类中的hashCode方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code equals} comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
上面其中一段解释了为什么需要重写
1 | * <li>If two objects are equal according to the {@code equals(Object)} |
换句话就是说
Java中规定如何两个对象通过equals方法得到的是true,那么返回的应该是同一个hashcode值,反过来如果两对象的hashcode值相同的话,这两个对象不一定相同,当然这两个对象都可能不是同一种类型,取决于怎么重写的hashcode。假设有这么一种情况,你往hashmap里面放了一个对象,但是你的这个对象里面只重写了equals方法但是没重写hashcode,因此我用另一个属性跟前面完全一样的对象,虽然equals方法返回是true,但是hashcode并没有重写,导致两个返回的是不同的整型值,而map的get方法会去判断key的hash值,不同的hashcode值必然导致这两个key不等,所以会拿到一个null值。
技术能力有限写不出来很高深的东西
成就感
但是比较有成就感的是这一次我竟然能够看懂别人写的ssm项目,第一个实习的时候好多地方都看不懂,可能是其他方面导致的比如项目需要所以看了redis的使用,redispool和redisconnectionfactory,用过了quartz,看完了mybatis文档,知道点security相关的东西,知道文件上传以及诸如此类的东西,看的东西越多,越来越感觉基础很重要,也知道了为什么招聘者会考一些基础知识。也是别人说的面试造飞机,上面拧螺丝。危机感很严重…..