Single

计算对象的哈希码

Java中创建的对象是保存在堆中,为了提高查找的速度而使用了散列查找。基本思想:定义一个键来映射对象所在的内存地址

当需要查找对象时,只需要查找键即可,这样就不用遍历整个堆内存来查找对象

public class Cat {
private String name;
private int age;
private double weight;
private Color color;
public Cat(String name, int age, double weight, Color color) {
this.name = name;
this.age = age;
this.weight = weight;
this.color = color;
}

//利用属性来判断Cat是否相同
@Override
public boolean equals(Object obj) {
if (this==obj) {//如果两个Cat是同一个对象则相同
return true;
}
if (obj==null) {//如果两个Cat有一个为null则不同
return false;
}
//如果两个Cat的类型不同则不同
if (getClass()!=obj.getClass()) {
return false;
}
Cat cat = (Cat)obj;
//比较属性
return name.equals(cat.name)&&(age==cat.age)&&
(weight==cat.weight)&&(color.equals(cat.color));
}
//hashCode()方法也是必须要写
public int hashCode(){
return 7 * name.hashCode()+11*new Integer(age).hashCode()+
13 * new Double(weight).hashCode() + 17 * color.hashCode();
}

@Override
public String toString() {
return “Cat [name=” + name + “, age=” + age + “, weight=” + weight
+ “, color=” + color + “]”;
}

}

测试:

public static void main(String[] args) {
Cat cat1 = new Cat(“Java”, 12, 21, Color.BLACK);
Cat cat2 = new Cat(“C++”, 12, 21, Color.WHITE);
Cat cat3 = new Cat(“Java”, 12, 21, Color.BLACK);
System.out.println(“Cat1号的哈希码:”+cat1.hashCode());
System.out.println(“Cat2号的哈希码:”+cat2.hashCode());
System.out.println(“Cat3号的哈希码:”+cat3.hashCode());
System.out.println(“Cat1是否与Cat2相同:”+cat1.equals(cat2));
System.out.println(“Cat1是否与Cat3相同:”+cat1.equals(cat3));
}

结果如下:

:http://www.linuxidc.com/Linux/2017-03/141917.htm