equal 如何重寫hashcode

如何重寫hashCode()和equals()方法

直接上刺刀了

定義一個學生類

class Student{

private String name;

private int age;

// getters and setters

}

重寫equal方法

重寫equal 使當學生的姓名和年齡相同時候就判斷他們為同一個學生

1. 判斷是否等於自身.

2使用instanceof運算符判斷 other 是否為Student類型的對象.

3. 比較Student類中你自定義的數據域,name和age,一個都不能少.

具體代碼如下

@Override

public boolean equals(Object other) {

System.out.println("equals method invoked!");

if(other == this)

return true;

if(!(other instanceof Student))

return false;

Studento = (Student)other;

return o.name.equals(name) && o.age == age;

}

重寫equals()而不重寫hashCode()的風險

構造一個hashset和兩個對象

Set set = new HashSet();

set.add(c1);

Studentc1 = new Student("yq1012", 10);

Studentc2 = new Coder("yq1012", 10);

System.out.println(set.contains(c2)); //結果為false

因此,我們重寫hashCode()的目的在於,在A.equals(B)返回true的情況下,A, B 的hashCode()要返回相同的值

如何重寫hashcode

@Override

public int hashCode() {

int result = 14;

result = result * 31 + name.hashCode();

result = result * 31 + age;

return result;

}

注:這裡最好重寫的時候不要返回固定值,如果hashCode()每次都返回相同的數,那麼所有的對象都會被放到同一個bucket中,每次執行查找操作都會遍歷鏈表,這樣就完全失去了哈希的作用

equal 如何重寫hashcode


分享到:


相關文章: