我想檢索HashMap中的另一個元素的值,覆蓋equals和hashcode方法。當我爲student1和student3使用相同的哈希碼並且這兩個對象相等時,爲什麼rollId返回null?理想的情況下,它應該返回我3.下面的代碼片段:Map HashCode和Equals
主類
public static void main(String[] args) {
Map<Student, Integer> studentMap = new HashMap<Student, Integer>();
Student student1 = new Student();
student1.setRollId(1);
Student student2 = new Student();
student2.setRollId(2);
studentMap.put(student1, 1);
studentMap.put(student2, 2);
for (Entry<Student, Integer> entry : studentMap.entrySet()) {
if (entry.getValue().equals(1)) {
student1.setRollId(3);
}
}
Student student3 = new Student();
student3.setRollId(3);
System.out.println("Student1 HashCode " + student1.hashCode()
+ " Student3 HashCode " + student3.hashCode());
System.out.println("Object Equal === > " + student1.equals(student3));
Integer rollId = studentMap.get(student3);
System.out.println("RollId is " + rollId);
}
學生班級
private Integer rollId;
public Integer getRollId() {
return rollId;
}
public void setRollId(Integer rollId) {
this.rollId = rollId;
}
@Override
public int hashCode() {
return rollId;
}
@Override
public boolean equals(Object obj) {
Student student = (Student)obj;
if(this.rollId.equals(student.getRollId()))
{
return true;
}
return false;
}
你應該張貼整個代碼,而不是片段讓助手可以測試你的代碼。 – 2014-08-30 18:18:34