正确重写equals()和hashCode()方法
来源:互联网 发布:欧洲旅游价格知乎 编辑:程序博客网 时间:2024/05/21 09:02
比较两个Java对象时, 如果相同的对象有不同的hashCode,比较操作会出现意想不到的结果,为了避免这种问题,要同时复写equals方法和hashCode方法,而不要只写其中一个。
class People { String name; int age; public People(String name, int age) { this.age = age; this.name = name; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof People)) { return false; } People people = (People) obj; return people.name.equals(name) && people.age == age; } @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); result = 31 * result + age; return result; }}public class Main { public static void main(String[] args) { People people1 = new People("程", 22); People people2 = new People("程", 22); People people3 = new People("程", 13); System.out.println(people1.equals(people2)); System.out.println(people1.equals(people3)); }}
运行结果
truefalse
0 0
- 正确重写equals()和hashCode()方法
- 如何正确的重写equals() 和 hashCode()方法
- 如何正确的重写equals() 和 hashCode()方法
- 重写hashCode和equals方法
- 重写equals和hashCode方法
- 重写hashCode和equals方法
- 重写hashcode和equals方法
- 重写equals() 和 hashCode()方法
- 重写hashCode()和equals()方法
- 重写equals和hashcode方法
- HashCode和equals方法重写
- 重写equals() 和 hashCode()方法
- 重写hashCode()方法和重写equals()方法
- 重写equals()方法和hashcode()方法
- 重写equals方法和hashcode方法
- HashMap中重写hashCode和equals方法
- java重写equals和hashCode方法
- 为什么要重写hashcode和equals方法
- caffe学习笔记12-建立自己的数据集与均值计算
- 异步网页采集利器CasperJs
- 2017.2.27-2017.3.5 第一个星期 header 直接生成xls导出
- poj 2406 Power Strings(KMP)
- 从 JVM 内存模型谈线程安全
- 正确重写equals()和hashCode()方法
- Linux入门(1)
- __blk_run_queue
- 小白用eclipse创建一个maven+web3.0+JDK1.7+tomcat7.0的web项目
- 分治求逆序数
- 四十年前的 6502 CPU 指令翻译成 JS 代码会是怎样
- Hibernate延迟加载机制详解
- Java的编程应该注意的问题
- jsp中的九大隐含对象和EL中的隐含对象