2015-05-16 120 views
2

這裏是我的代碼,確保添加學生信息與姓名,年齡和地址。爲了確保學生是獨一無二的。我使用hashCode()equals()來確保數據的完整性。學生的同一名稱將被視爲覆蓋。即使通過hashCode()和equals()也不能重寫Hashmap元素?

問題是:相同的信息永遠不會被清除,任何人都知道爲什麼?看來hashCode()equals()從來沒有工作。

class Student implements Comparable<Student>{ 

    private String name; 
    private int age; 

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

     return name.hashCode() + age *34; 
    } 

    //override equals method 
    public boolean equals(Object obj){ 
     if(!(obj instanceof Student)) 
      throw new ClassCastException("The data type is not match!"); 

     Student s = (Student)obj; 
     return this.name.equals(s.name) && this.age==s.age; 
    } 

    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public int getAge() { 
     return age; 
    } 
    public void setAge(int age) { 
     this.age = age; 
    } 
    @Override 
    public int compareTo(Student s) { 
     int num = new Integer(this.age).compareTo(new Integer(s.age)); 
     if (num == 0) 
       return this.name.compareTo(s.name); 
     return num; 
    } 
} 

public class HashMapDemo1 { 

    public static void main (String[] agrs){ 

     HashMap<Student,String> hs = new HashMap<Student,String>(); 

     hs.put(new Student("James",27),"Texas"); 
     hs.put(new Student("James",27), "California"); 
     hs.put(new Student("James",27), "New mexico"); 

     hs.put(new Student("Jack",22),"New York"); 
     hs.put(new Student("John",25),"Chicago"); 
     hs.put(new Student("Francis",26),"Florida"); 

     Set<Student> Keyset = hs.keySet(); 
     Iterator<Student> it = Keyset.iterator(); 

     while(it.hasNext()){ 
      Student stu = it.next(); 
      String addr = hs.get(stu); 
      System.out.print(stu.getName()+stu.getAge()+"..." +addr+"\n"); 
     } 
} 
+3

程序的輸出是什麼? – Radiodef

+0

班學生實施可比較,通用是學生。當我把它放在頁面上時,我錯過了它。 –

+2

順便說一句,如果'obj'不是'Student'的一個實例,'equals'不應該拋出'ClassCastException',它應該返回false。 – Radiodef

回答

4

hashcode != hashCode

確保當你認爲你是覆蓋了超類的方法來使用@Override註解,因爲這將讓編譯器通知您,如果/當你錯了。正如你發現的那樣,在編譯階段修復錯誤比在運行階段更容易。

我自己,我不會使用年齡字段作爲equals或hashCode的一部分,因爲隨着時間的推移,年齡可能會隨着時間而改變。我會使用Date birthDate或其他一些不變。

而且我同意Radiodef:equals(...)方法不應該拋出異常。如果參數對象不是Student類型,只需返回false。

+0

非常感謝!這是一個粗心的錯誤。 –

+0

你好,順便說一句,我沒有返回false的原因是我想讓代碼可以給出更多的反饋,如果異常發生。如果我只是返回錯誤,那麼我就無法從中得到答案。有沒有更好的方法來做到這一點? –

+0

在編寫類型安全的代碼時(例如,不使用具有[原始類型]的集合(https:// docs)),不應該有任何理由比較'Student'與另一個類的實例的等同性。 .oracle.com/JavaSE的/教程/ JAVA /泛型/ rawTypes.html))。 –

1

您實施的方法是public int hashcode()。 它應該是public int hashCode()

+0

謝謝,這是一個愚蠢的錯誤。 –

相關問題