2013-08-02 50 views
6

//Student.java如何使用原始的hashCode()方法覆蓋其

class Student{ 
private int roll; 
private String name; 

    public Student(int roll,String name){ 
    this.roll=roll; 
    this.name=name; 
    } 

    public int hashCode(){ 
    return roll+name.length(); 
    } 

    public boolean equals(Object obj){ 
    Student s=(Student)obj; 
    return (this.roll==s.roll && this.name.equals(s.name)); 
    } 

} 

//IssueID.java

class IssueID{ 

    public static void issueID(Student s1,Student s2){ 

    if(s1.equals(s2)) 
    System.out.println("New ID issued"); 

    else 
    System.out.println("New ID NOT issued"); 

    } 

} 

//Institute.java

import java.lang.Object; 
class Institute{ 
    public static void main(String[] args){ 
    Student s1=new Student(38,"shiva"); 
    Student s2=new Student(45,"aditya"); 

    IssueID.issueID(s1,s2); 


    System.out.println(s1.hashCode()); 
    System.out.println(s2.hashCode()); 
    } 

} 

後正如在上面的代碼中,我已經覆蓋了hashCode()方法。這聽起來很愚蠢,但我可以同時使用相同的Student對象(s1和s2)訪問java.lang.Object.hashCode()方法嗎?

+1

'super.hashCode(',但是這將是沒有用的恕我直言。 –

回答

17

是,與System.identityHashCode

返回相同的散列碼爲給定的對象會被默認的方法的hashCode(返回),給定對象的類是否重寫hashCode()。

0

您可以使用System.identityHashCodesuper.hashCode()此外,你應該寫一個更好的散列碼與任何學生名字的長度之和滾動等於將具有相同的哈希碼。像(9,「鮑勃」)和(7,「史蒂夫」)。這將爲未來的錯誤開闢許多潛在的問題。保存自己的頭痛並寫下如下內容:

public int hashCode() { 
     int hash = 31 * roll; 
     hash = 31 * hash + name.hashCode(); 
     return hash; 
} 

另外,請注意,您的equals方法不滿足JLS中的equals方法。

this.equals(null)應該返回false,你的將拋出一個ClassCastException。

這也可能導致未來的錯誤。

+0

是啊!該hashcode方法僅用於測試。無論如何感謝您的建議! –

+1

[HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html)是你的朋友! – chrylis

0

寫這樣的事情:

class Student { 
    public int originalHashCode() { 
     return super.hashCode(); 
    } 
} 

然後調用s.originalHashCode()當您想使用)原來〜