java hashCode与equals函数

前言

  • equals 与 == 的区别

  • hashCode与equals之间的联系

  • 什么情况下需要重写hashCode与equals函数

equals 与 == 的区别

Object equals()方法:

public boolean equals(Object obj) {
return (this == obj);
}

== : 作用是判断两个对象的地址是不是相等。即判断两个对象是不是同一个对象。

equals() : 作用是判断两个对象是否相等。但它一般有两种使用情况:

情况1,类没有覆盖equals()方法。则通过equals()比较该类的两个对象时,等价于通过“==”比较这两个对象。
情况2,类覆盖了equals()方法。一般,我们都覆盖equals()方法来两个对象的内容相等;若它们的内容相等,则返回true。

所以,当我们需要比较两个对象的内容是否相等时,则需要重写继承自Object类中的equals(Object obj)方法,例如:java.lang.String等。

hashCode与equals联系

为了满足Map,Set等哈希表的约定,要求两个对象的equals值相等,则hashCode的值一定要相等,但是hashCode的值相等,equals值不一定相等。所以,当自定义的对象要作为Key存入Map或Set时要重写和哈希表密切相关的两个函数hashCode和equals函数。

实现案例

public class ChannelBean {

public String channel = null;
public String host = null;
public int port = 0;

public ChannelBean(String channel, String host, int port) {
this.channel = channel;
this.host = host;
this.port = port;

}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((channel == null) ? 0 : channel.hashCode());
result = prime * result + ((host == null) ? 0 : host.hashCode());
result = prime * result + port;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ChannelBean other = (ChannelBean) obj;
if (channel == null) {
if (other.channel != null) return false;
} else if (!channel.equals(other.channel) || !host.equals(other.host) || port != other.port) {
return false;
}
return true;
}