为什么重写?
在项目开发中遇到需要将Object对象作为HashMap的key使用的场景,为了保证HashMap的key的唯一性,故对该对象进行了重写hashCode方法和重写equals方法。
代码示例
package com.xxx.xxx;
/**
* @Author:
* @Date:
* @Description:
*/
public class ColumnDTO {
private String columnid;
private String columnname;
private String nodepath;
private String upperid;
private String linkurl;
public String getColumnid() {
return columnid;
}
public void setColumnid(String columnid) {
this.columnid = columnid;
}
public String getColumnname() {
return columnname;
}
public void setColumnname(String columnname) {
this.columnname = columnname;
}
public String getNodepath() {
return nodepath;
}
public void setNodepath(String nodepath) {
this.nodepath = nodepath;
}
public String getUpperid() {
return upperid;
}
public void setUpperid(String upperid) {
this.upperid = upperid;
}
public String getLinkurl() {
return linkurl;
}
public void setLinkurl(String linkurl) {
this.linkurl = linkurl;
}
/**
* 重写hashCode方法和equals方法,保证该对象可以当作HashMap的Key使用
*/
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (columnid == null ? 0 : columnid.hashCode());
result = 31 * result + (columnname == null ? 0 : columnname.hashCode());
result = 31 * result + (nodepath == null ? 0 : nodepath.hashCode());
result = 31 * result + (upperid == null ? 0 : upperid.hashCode());
result = 31 * result + (linkurl == null ? 0 : linkurl.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;//地址相等
}
if(obj == null){
return false;//非空性:对于任意非空引用x,x.equals(null)应该返回false。
}
if(obj instanceof ColumnDTO){
ColumnDTO other = (ColumnDTO) obj;
//需要比较的字段相等,则这两个对象相等
if(this.columnid.equals(other.columnid)
&& this.columnname.equals(other.columnname)
&& this.nodepath.equals(other.nodepath)
&& this.linkurl.equals(other.linkurl)
&& this.upperid.equals(other.upperid)){
return true;
}
}
return false;
}
}
突出重点及总结
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (columnid == null ? 0 : columnid.hashCode());
result = 31 * result + (columnname == null ? 0 : columnname.hashCode());
result = 31 * result + (nodepath == null ? 0 : nodepath.hashCode());
result = 31 * result + (upperid == null ? 0 : upperid.hashCode());
result = 31 * result + (linkurl == null ? 0 : linkurl.hashCode());
return result;
}
需要对每一个成员变量进行类似的hashCode处理,将最终的结果返回作为hashCode值。
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;//地址相等
}
if(obj == null){
return false;//非空性:对于任意非空引用x,x.equals(null)应该返回false。
}
if(obj instanceof ColumnDTO){
ColumnDTO other = (ColumnDTO) obj;
//需要比较的字段相等,则这两个对象相等
if(this.columnid.equals(other.columnid)
&& this.columnname.equals(other.columnname)
&& this.nodepath.equals(other.nodepath)
&& this.linkurl.equals(other.linkurl)
&& this.upperid.equals(other.upperid)){
return true;
}
}
return false;
}
需要对每一个成员变量进行比较,所有成员变量都相同才返回true,否则返回false。