/**
*
*/
package cn.fsf.annotation;
/**
* this class shows that how to write a proper hashCode()
*
* @author FSF
*
*/
public class HashCodeExample {
private boolean aBoolean = true;
private byte aByte = 1;
private char aChar = 'd';
private int aInt = 10;
private long aLong = 30;
private float aFloat = 89;
private double aDouble = 90.34;
private String aStr = "test";
private String[] aArray = { "df", "cs" };
@Override
public int hashCode() {
int lResult = 17;
// first step,collect all usefull fields hashCode in a proper way,
// the principle is that the code must generate fast and simple
int lBooleanCode = aBoolean ? 1 : 0;
int lByteCode = aByte;
int lCharCode = aChar;
int lIntCode = aInt;
int lLongCode = (int) (aLong ^ (aLong >>> 32));
int lFloatCode = Float.floatToIntBits(aFloat);
long lDoubleCodeTemp = Double.doubleToLongBits(aDouble);
int lDoubleCode = (int) (lDoubleCodeTemp ^ (lDoubleCodeTemp >>> 32));
int lStrCode = aStr.hashCode();
int lArrayCode = 0;
if (aArray != null && aArray.length > 0) {
for (int i = 0; i < aArray.length; i++) {
lArrayCode += aArray[i].hashCode();
}
}
// get the sum of them
int lSumCode = lBooleanCode + lByteCode + lCharCode + lIntCode
+ lLongCode + lFloatCode + lDoubleCode + lStrCode + lArrayCode;
// generate the hashCode
lResult = 31 * lResult + lSumCode;
return lResult;
}
public static void main(String[] args) {
HashCodeExample lExample = new HashCodeExample();
System.out.println(lExample.hashCode());
}
}
分享到:
相关推荐
实际上,hashcode根本不能代表object的内存地址。
深入 HashCode 方法~~~~~
Object类的hashCode的用法 马克-to-win java视频哈希码
hashcode是用来查找的,如果你学过数据结构就应该知道,在查找和排序这一章有……
hashcode的作用.doc hashcode的作用.doc hashcode的作用.doc
1.hashcode是用来查找的,如果你学过数据结构就应该知道,在查找和排序这一章有 例如内存中有这样的位置 0 1 2 3 4 5 6 7 而我有个类,这个类有个字段叫ID,我要把这个类存放在以上8个位置之一,如果不用hashcode...
重写equals和hashcode方法,学习和进步
这里是一个文档,里边讲解了hashCode与equals方法使用,大家要是不明白,可以去看看
equals()和hashcode()这两个方法都是从object类中继承过来的。当String 、Math、还有Integer、Double。。。。等这些封装类在使用equals()方法时,已经覆盖了object类的equals()方法.
PPT浅析hashcode定义和作用;和简单的代码演示PPT.很简单的
java中hashCode()的理解
java中Hashcode的作用
深入HashCode 最近学习HashCode的小结与整理,希望对大家有帮助
1,如果两个对象相同,那么它们的hashCode值一定要相同; 2,如果两个对象的hashCode相同,它们并不一定相同 上面说的对象相同指的是用eqauls方法比较。 3,HashCode码不唯一
利用反射绕过编译器和hashcode高级应用
Java重写equals同时需要重写hashCode的代码说明,以及如何重写hashCode方法,此代码演示按照effective java书籍说明的重写思路。代码中演示了使用集合存储对象,并且对象作为key,需重写equals和hashCode.
本文介绍了Java语言不直接支持关联数组,可以使用任何对象作为一个索引的数组,但在根Object类中使用 hashCode()方法明确表示期望广泛使用HashMap。理想情况下基于散列的容器提供有效插入和有效检索;直接在对象模式...
HashCode相同equals不同的2位字符集合算法 另附ASCII码表
-- Build files have been written to: ~ /hashcode/cpp/build $ make ... [100%] Built target hashcode $ ./hashcode Usage: ./hashcode [-io] [-i input][-o output] ... C ++结果 1. A – An example: 2,000
深入解析Java对象的equals()和hashCode()的使用 在Java语言中,equals()和hashCode()两个函数的使用是紧密配合的,你要是自己设计其中一个,就要设计另外一个。在多数情况下,这两个函数是不用考虑的,直接使用它们...