package com.sample;
import java.util.HashMap;
class Student{
int id;
@Override
public int hashCode() {
return -1;
}
@Override
public boolean equals(Object obj) {
return false; // returning false
}
}
public class MainClass {
public static void main(String[] args) {
Student s1=new Student();
s1.id=123;
Student s2=new Student();
s2.id=456;
HashMap<Student,String> s=new HashMap<Student,String>();
s.put(s1, "One");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
s.put(s2, "Two");
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
s.put(s1, "Three");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println("after insert");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
}
}
OUTPUT
< s1 value > One < s1 hashcode > 79430
< s2 value > Two < s2 hashcode > 84524
< s1 value > Three < s1 hashcode > 80786814
after insert
< s1 value > Three < s1 hashcode > 80786814 //printing three for s1
< s2 value > Two < s2 hashcode > 84524 //printing two for s2
//現在,如果我們改變equals方法的返回類型爲true,輸出的變化無一不返回三個作爲輸出。我無法理解,如果我們改變equals方法的返回類型,爲什麼輸出會改變。請用bucket(HashMap)和equals方法的上下文來解釋。如果我們改變equals方法的返回值,爲什麼輸出會改變?
class Student{
int id;
@Override
public int hashCode() {
return -1;
}
@Override
public boolean equals(Object obj) {
return true; //returning true
}
}
public class MainClass {
public static void main(String[] args) {
Student s1=new Student();
s1.id=123;
Student s2=new Student();
s2.id=456;
HashMap<Student,String> s=new HashMap<Student,String>();
s.put(s1, "One");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
s.put(s2, "Two");
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
s.put(s1, "Three");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println("after insert");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
}
}
OUTPUT-
< s1 value > One < s1 hashcode > 79430
< s2 value > Two < s2 hashcode > 84524
< s1 value > Three < s1 hashcode > 80786814
after insert
< s1 value > Three < s1 hashcode > 80786814 //printing three for s1
< s2 value > Three < s2 hashcode > 80786814 //printing three for s2
請參考[爲什麼map使用equals方法檢查鍵](http://stackoverflow.com/questions/31860486/does-a-map-using-equals-method-for-key-checking-exists) –