2015-05-16 37 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

谢谢,这是一个愚蠢的错误。 –

相关问题