override equals in Java
equals() (javadoc) must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.
hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).
The relation between the two methods is:
Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
Steps to Override equals method in Java
return false;
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute equals() to compute hashCode().
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Langlibrary. An example:
public class Person {
private String name;
private int age;
// ...
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Person))
return false;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
OR
/**
* Person class with equals and hashcode implementation in Java
* @author Javin Paul
*/
public class Person {
private int id;
private String firstName;
private String lastName; public int getId() { return id; }
public void setId(int id) { this.id = id;} public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
} Person guest = (Person) obj;
return id == guest.id
&& (firstName == guest.firstName
|| (firstName != null && firstName.equals(guest.getFirstName())))
&& (lastName == guest.lastName
|| (lastName != null && lastName .equals(guest.getLastName())));
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + id;
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
} }
Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, orWeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.
override equals in Java的更多相关文章
- Effective Java 09 Always override hashCode when you override equals
Failure to do so will result in a violation of the general contract for Object.hashCode, which will ...
- Java之所有对象的公用方法>9.Always override hashCode when you override equals
You must override hashCode in every class that overrides equals.
- 使用hashCode()和equals()方法 - Java
在这篇文章中,我将指出我对hashCode()和equals()方法的理解.我将讨论它们的默认实现以及如何正确地覆盖它们.我还将使用Apache Commons包中的实用工具类来实现这些方法. has ...
- C# abstract virtual override new finally java final finalize
virtual:声明虚方法.可以被其派生类所重写的.重写方法需要使用override或者new关键字. override:覆盖原方法.可对重写virtual.override.abstract进行重写 ...
- 关于==和equals()方法&Java中string与char如何转换&String,StringBuffer
1.对于基本数据类型,可以直接使用==和!=进行内容比较 如:int x=30; int y=30; x==y; //true 基本数据类型 简单类型(基本类型) bo ...
- Overload and Override without Overwrite - Java
Override(覆盖/覆写): 子类Override父类中的函数(方法).Overload(重载): 同一个类中包含多个同名的函数(方法), 但各个函数的参数列表不同. Override和Overl ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- Core Java Interview Question Answer
This is a new series of sharing core Java interview question and answer on Finance domain and mostly ...
- 200个最常见的JAVA面试问题(附答案)
本文内容: 20个最常见的JAVA面试问题(附答案) 13个单例模式JAVA面试问题(附答案) 说说JVM和垃圾收集是如何工作的(附答案) 说说如何避免JAVA线程死锁(附答案) Java中HashS ...
随机推荐
- GVIM:在WINDOWS下清爽写代码
上大学后,你是不是也开始学习C语言了?特别是计算机学院的孩子,应当有更高的追求.C语言开课一段时间了,你是不是开始嫌弃IDE恶心的界面了?是不是跟我一样,嫌弃IDE打开速度太慢?VS2010需要12秒 ...
- document.write() 和 document.writeln() 区别
写javascript页面时,看到这两个函数,第一感觉应该是一个换行,一个不换行, 但是实际使用时是一样的(writeln()函数在浏览器页面会多一个空格而不是换行). 简单搜索查阅了下: 查看源 d ...
- Android:WebView中对图片注册上下文菜单
前言 今天一朋友问我一个问题,就是如何在WebView控件中的图片增加上下文菜单,以便增加保存图片等功能.今天就给他简单做了一个演示Demo,现写下来,给有相同问题的朋友提供些许思路吧. 概要实现 其 ...
- JavaScript移除数组元素减少长度的方法
JavaScript移除数组元素减少长度的方法,代码如下: //数组移除长度方法 var array=[]; array[0]="张三"; array[1]="李四& ...
- 百度云demo2
- BI与大数据
微博的诞生.云计算.物联网.移动互联网等各种爆炸式数据,给商业智能的蓬勃发展提供了良好的“大数据”环境.大数据为BI带来了海量数据.对挖掘来说,大数据量要更容易对比.抢夺大数据市场,需要具备一定的实力 ...
- orcale 修改字段属性
有些时候,因为没能预料到一些情况的变化,需要修改字段的类型.如果是varchar型,直接增加长度是可以的,但是如果需要修改成其他类型就不能这么做了. 思路:1.增加一个临时列,把需要修改的那个字段的数 ...
- windows2003服务器不显示桌面怎么办
ctrl +alt+delete 进入任务管理器应用程序里 创建新任务 C:\WINDOWS\explorer.exe 运行就行
- MVC学习系列——RazorViewEngine扩展
有时候,我们的项目涉及到多种风格,我们可以通过扩展RazorViewEngine,这样就可以保持后台代码不发生变化. 新建类ThemeViewEngine继承于RazorViewEngine publ ...
- 二、有限状态机(FSM)
1.状态机的作用?是什么? 状态机,顾名思义就是用来描述状态的.完善一点就是在同一的时钟下.更准确说是一种verilogHDL编程思想. 例如我们每一个系统都可以分为好几种状态,如:开始,初始化,运行 ...