- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章java中为何重写equals时必须重写hashCode方法详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
前言 。
大家都知道,equals和hashcode是java.lang.object类的两个重要的方法,在实际应用中常常需要重写这两个方法,但至于为什么重写这两个方法很多人都搞不明白.
在上一篇博文java中equals和==的区别中介绍了object类的equals方法,并且也介绍了我们可在重写equals方法,本章我们来说一下为什么重写equals方法的时候也要重写hashcode方法.
先让我们来看看object类源码 。
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
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
37
38
39
40
41
42
43
44
45
46
47
48
49
|
/**
* indicates whether some other object is "equal to" this one.
* <p>
* the {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>it is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>it is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>it is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>it is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>for any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* the {@code equals} method for class {@code object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* note that it is generally necessary to override the {@code hashcode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashcode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashcode()
* @see java.util.hashmap
*/
public
boolean
equals(object obj) {
return
(
this
== obj);
}
|
hashcode:是一个native方法,返回的是对象的内存地址, 。
equals:对于基本数据类型,==比较的是两个变量的值。对于引用对象,==比较的是两个对象的地址.
接下来我们看下hashcode的注释 。
1.在 java 应用程序执行期间,在对同一对象多次调用 hashcode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。 从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。 2.如果根据 equals(object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashcode 方法都必须生成相同的整数结果。 3.如果根据 equals(java.lang.object) 方法,两个对象不相等,那么两个对象不一定必须产生不同的整数结果。 但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能.
从hashcode的注释中我们看到,hashcode方法在定义时做出了一些常规协定,即 。
1,当obj1.equals(obj2) 为 true 时,obj1.hashcode() == obj2.hashcode() 。
2,当obj1.equals(obj2) 为 false 时,obj1.hashcode() != obj2.hashcode() 。
hashcode是用于散列数据的快速存取,如利用hashset/hashmap/hashtable类来存储数据时,都是根据存储对象的hashcode值来进行判断是否相同的。如果我们将对象的equals方法重写而不重写hashcode,当我们再次new一个新的对象的时候,equals方法返回的是true,但是hashcode方法返回的就不一样了,如果需要将这些对象存储到结合中(比如:set,map ...)的时候就违背了原有集合的原则,下面让我们通过一段代码看下.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/**
* @see person
* @param args
*/
public
static
void
main(string[] args)
{
hashmap<person, integer> map =
new
hashmap<person, integer>();
person p =
new
person(
"jack"
,
22
,
"男"
);
person p1 =
new
person(
"jack"
,
22
,
"男"
);
system.out.println(
"p的hashcode:"
+p.hashcode());
system.out.println(
"p1的hashcode:"
+p1.hashcode());
system.out.println(p.equals(p1));
system.out.println(p == p1);
map.put(p,
888
);
map.put(p1,
888
);
map.foreach((key,val)->{
system.out.println(key);
system.out.println(val);
});
}
|
equals和hashcode方法的都不重写 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
person
{
private
string name;
private
int
age;
private
string sex;
person(string name,
int
age,string sex){
this
.name = name;
this
.age = age;
this
.sex = sex;
}
}
|
1
2
3
4
5
6
|
p的hashcode:
356573597
p1的hashcode:
1735600054
false
false
com.blueskyli.练习.person
@677327b6
com.blueskyli.练习.person
@1540e19d
|
只重写equals方法 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
class
person
{
private
string name;
private
int
age;
private
string sex;
person(string name,
int
age,string sex){
this
.name = name;
this
.age = age;
this
.sex = sex;
}
@override
public
boolean
equals(object obj)
{
if
(obj
instanceof
person){
person person = (person)obj;
return
name.equals(person.name);
}
return
super
.equals(obj);
}
}
|
1
2
3
4
5
6
|
p的hashcode:
356573597
p1的hashcode:
1735600054
true
false
com.blueskyli.练习.person
@677327b6
com.blueskyli.练习.person
@1540e19d
|
equals和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
|
public
class
person
{
private
string name;
private
int
age;
private
string sex;
person(string name,
int
age,string sex){
this
.name = name;
this
.age = age;
this
.sex = sex;
}
@override
public
boolean
equals(object obj)
{
if
(obj
instanceof
person){
person person = (person)obj;
return
name.equals(person.name);
}
return
super
.equals(obj);
}
@override
public
int
hashcode()
{
return
name.hashcode();
}
}
|
1
2
3
4
5
|
p的hashcode:
3254239
p1的hashcode:
3254239
true
false
com.blueskyli.练习.person
@31a7df
|
我们知道map是不允许存在相同的key的,由上面的代码可以知道,如果不重写equals和hashcode方法的话会使得你在使用map的时候出现与预期不一样的结果,具体equals和hashcode如何重写,里面的逻辑如何实现需要根据现实当中的业务来规定.
总结:
1,两个对象,用==比较比较的是地址,需采用equals方法(可根据需求重写)比较.
2,重写equals()方法就重写hashcode()方法.
3,一般相等的对象都规定有相同的hashcode.
4,string类重写了equals和hashcode方法,比较的是值.
5,重写hashcode方法为了将数据存入hashset/hashmap/hashtable(可以参考源码有助于理解)类时进行比较 。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我的支持.
原文链接:https://www.cnblogs.com/blueskyli/p/9936076.html 。
最后此篇关于java中为何重写equals时必须重写hashCode方法详解的文章就讲到这里了,如果你想了解更多关于java中为何重写equals时必须重写hashCode方法详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!