在自定义的一个数据类中 重写equals和HashCode以防止重复输入相同数据
public class Department {
String depCode;
public int hashCode()
{
// System.out.println("————————执行了Department.hashCode()——————");
return 7*depCode.hashCode();
}
//一个判断对象是否相等的equals
public boolean equals(Object Department)
{
// System.out.println("----------执行了Department.equals()--------");
// 一个快速测试,看看对象是相同的
if (this==Department) return true;
// 如果显示的参数是空的时候 则必须返回错误
if(Department==null) return false;
// 如果类型不匹配 则不可能相等 getclass 将返回对象所属的类
if(getClass()!=Department.getClass())
return false;
// 现在我们知道Department 是一个非空的部门了
Department other =(Department)Department;
//测试是否有相同的值的字段
return depCode.equals(other.depCode);
//&& depName.equals(other.depName);
}
}
然后在另一个类中向Department中put数据的时候 会自动调用HashCode 如果HashCode为true ,则调用equals继续判断是否有相同的,若equals也为true 则说明put的数据相同 则不加入。