[code=java]package com.entity;
public class Student {
private String name;
private int age;
private double score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(score) != Double
.doubleToLongBits(other.score))
return false;
return true;
}
}[/code][code=java] public static void main(String[] args) {
Collection collections = new HashSet();
Student s1 = new Student ("a",3,3);
Student s2 = new Student ("b",5,5);
Student s3 = new Student ("a",3,3);
collections.add(s1);
collections.add(s2);
collections.add(s3);
System.out.println(collections.size());
}[/code]输出2
如果不覆盖hashCode方法和equals方法就输出3
单对hashcode解释一下, hashcode只有类的实例对象要被采用哈希算法惊醒存储和检索时,这个类才需要按要求覆盖hashcode方法。即使程序可能暂时不会用到当前类的hashCode方法,但是为他提供一个hashcode方法也不会又什么不好,没准以后什么时候又用到这个方法,所以,通常要求hashCode方法和equals方法一并同时覆盖。 |