我已經寫具有Student類和學生目的如下被用作鍵 一個代碼,什麼是hashmap碰撞?並在我的代碼中發生?
public class ExampleMain01 {
private static class Student{
private int studentId;
private String studentName;
Student(int studentId,String studentName){
this.studentId = studentId;
this.studentName = studentName;
}
@Override
public int hashCode(){
return this.studentId * 31;
}
@Override
public boolean equals(Object obj){
boolean flag = false;
Student st = (Student) obj;
if(st.hashCode() == this.hashCode()){
flag = true;
}
return flag;
}
@Override
public String toString(){
StringBuffer strb = new StringBuffer();
strb.append("HASHCODE ").append(this.hashCode())
.append(", ID ").append(this.studentId)
.append(", NAME ").append(this.studentName);
return strb.toString();
}
public int getStudentId() {
return studentId;
}
public String getStudentName() {
return studentName;
}
} // end of class Student
private static void example02() throws Exception{
Set<Student> studentSet = new HashSet<Student>();
studentSet.add(new Student(12, "Arnold"));
studentSet.add(new Student(12, "Sam"));
studentSet.add(new Student(12, "Jupiter"));
studentSet.add(new Student(12, "Kaizam"));
studentSet.add(new Student(12, "Leny"));
for(Student s : studentSet){
System.out.println(s);
}
} // end of method example02
private static void example03() throws Exception{
Map<Student, Integer> map = new HashMap<Student,Integer>();
Student[] students = new Student [] {
new Student(12, "Arnold"),
new Student(12, "Jimmy"),
new Student(12, "Dan"),
new Student(12, "Kim"),
new Student(12, "Ubzil")
};
map.put(students[0], new Integer(23));
map.put(students[1], new Integer(123));
map.put(students[2], new Integer(13));
map.put(students[3], new Integer(25));
map.put(students[4], new Integer(2));
Set<Map.Entry<Student, Integer>> entrySet = map.entrySet();
for(Iterator<Map.Entry<Student, Integer>> itr = entrySet.iterator(); itr.hasNext();){
Map.Entry<Student, Integer> entry = itr.next();
StringBuffer strb = new StringBuffer();
strb.append("Key : [ ").append(entry.getKey()).append(" ], Value : [ ").append(entry.getValue()).append(" ] ");
System.out.println(strb.toString());
}
} // end of method example03
public static void main(String[] args) {
try{
example02();
example03();
}catch(Exception e){
e.printStackTrace();
}
}// end of main method
} // end of class ExampleMain01
在Student類上面的代碼的哈希碼和equals是這樣實現的,
@Override
public int hashCode(){
return this.studentId * 31;
}
@Override
public boolean equals(Object obj){
boolean flag = false;
Student st = (Student) obj;
if(st.hashCode() == this.hashCode()){
flag = true;
}
return flag;
}
現在,當我編譯和運行該代碼,
在方法example02的代碼給出的輸出作爲
HASHCODE 372, ID 12, NAME Arnold
即設置只保存一個對象,
我明白,作爲所有對象的鍵具有相同的hashCode因此只有單一的目的在於,水桶372我說得對不對?
同樣方法example03()得到輸出作爲
Key : [ HASHCODE 372, ID 12, NAME Arnold ], Value : [ 2 ]
從我們可以看到,作爲密鑰返回相同的散列碼, HashMap中僅保持單一密鑰值對上述方法。
所以我的問題是沒有衝突發生在哪裏?
可以一鍵可以指向多個值嗎?
哪裏LinkedList的概念來而尋找各個鍵的值?
可有人請給我解釋一下上面的東西對於我有共同的例子嗎?
哈希衝突不是一個問題,你的問題是,你提供平等的ID,你只檢查在'equals'事實方法。 – Tom