重写hashCode方法
来源:互联网 发布:java项目有意思的案例 编辑:程序博客网 时间:2024/04/19 18:42
hashCode方法在Object类中定义如下:
public native int hashCode();
说明是一个本地方法,其实现和本地机器相关。我们可以在自己的类中覆盖hashCode方法。
下面String类中重写的hashCode方法:
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
}
hash = h;
}
return h;
}
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++]; }
hash = h;
}
return h;
}
下面是重写hashCode方法的例子:
public class Action
{
private String deviceMacAddr;
private String attribute;
private String operation;
private String value;
{
private String deviceMacAddr;
private String attribute;
private String operation;
private String value;
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((attribute == null) ? 0 : attribute.hashCode());
result = prime * result+ ((deviceMacAddr == null) ? 0 : deviceMacAddr.hashCode());
result = prime * result+ ((operation == null) ? 0 : operation.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((attribute == null) ? 0 : attribute.hashCode());
result = prime * result+ ((deviceMacAddr == null) ? 0 : deviceMacAddr.hashCode());
result = prime * result+ ((operation == null) ? 0 : operation.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
}
几点说明:
1. equals()相等的两个对象,hashcode()一定相等;
2. equals()不相等的两个对象,却并不能证明他们的hashcode()不相等。换句话说,equals()方法不相等的两个对象,hashcode()有可能相等。
2. equals()不相等的两个对象,却并不能证明他们的hashcode()不相等。换句话说,equals()方法不相等的两个对象,hashcode()有可能相等。
3. hashcode()不等,一定能推出equals()也不等;hashcode()相等,equals()可能相等,也可能不等。
0 0
- 重写一下hashCode方法
- 重写 hashCode 方法
- 重写hashCode方法
- 如何重写hashcode方法
- 重写hashCode方法
- 重写hashCode方法
- 重写hashCode()方法
- 重写hashCode方法
- hashcode的重写方法
- 重写hashCode()方法和重写equals()方法
- 重写自己的hashCode()方法
- 重写自己的hashCode()方法
- 重写自己的hashCode()方法
- 重写hashCode和equals方法
- 为什么要重写hashcode() 方法
- 重写Object中的hashCode方法
- 重写equals和hashCode方法
- 重写hashCode和equals方法
- 使用CopyTable工具方法在线备份HBase表
- Hate the VIN, Wanna Change It?
- CentOS 5.8 linux下搭建LEMP平台
- C#复制数据库,将数据库数据转到另一个数据库
- 有商业构想没经验?这些创始人证明即使这样也能成功
- 重写hashCode方法
- Android 自动生成的R类
- Android将View转为Bitmap
- 1002. 写出这个数 (20)
- 多线程下载 关键代码
- 设计模式——单例模式(Singleton Pattern)
- pdf格式转换器使用步骤
- 重写equals方法
- 使用openwrt屏蔽广告(包括视频前的广告)