1. 使用eclipse生成hashCode方法, 模拟一个两个对象实例不同, hashCode形同, 两个对象的equals方法返回flase的场景。
1.1. People类
public class People {
int id;
String name;
int age;
public People(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
/**
* eclipse功能生成hashCode方法
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
/**
* eclipse功能生成equals方法
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (id != other.id)
return false;
return true;
}
}
1.2. Student类
public class Student {
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
/**
* eclipse功能生成hashCode方法
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
/**
* eclipse功能生成equals方法
*/
@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 (id != other.id)
return false;
return true;
}
}
1.3. MyHashCode类
public class MyHashCode {
public static void main(String[] args) {
People xiaoming = new People(9001, "xiaoming", 22);
Student xiaocui = new Student(9001, "xiaocui", 16);
// 对象不同, hashCode相等
System.out.println("xiaocui hashCode = " + xiaoming.hashCode() + " xiaocui hashCode = " + xiaocui.hashCode());
// 对象不同, hashCode相等, 两个对象的equals返回false
System.out.println(xiaoming.equals(xiaocui));
}
}
1.4. 输出:
xiaocui hashCode = 9032 xiaocui hashCode = 9032
false