这是我的代码,请确保添加姓名,年龄和地址的学生信息。为了确保学生是独一无二的。我使用hashCode()
和equals()
来确保数据完整性。学生的同名将被视为覆盖。
问题是:永远不会清除相同的信息,有人知道为什么吗?似乎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");
}
}
答案 0 :(得分:4)
hashcode != hashCode
每当您认为重写超类方法时,请务必使用@Override
注释,因为这样可以让编译器在您错误时通知您。正如您所发现的那样,在编译阶段而不是运行阶段修复错误要容易得多。
我自己,我不会将年龄字段用作equals或hashCode的一部分,因为随着时间的推移,学生的年龄会发生变化。我会使用Date birthDate
或其他一些不变量。
我同意Radiodef:equals(...)
方法不应该抛出异常。如果参数对象不是学生类型,则只返回false。
答案 1 :(得分:1)
您实施的方法是public int hashcode()
。
它应该是public int hashCode()
。