這裏是我的代碼,確保添加學生信息與姓名,年齡和地址。爲了確保學生是獨一無二的。我使用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");
}
}
程序的輸出是什麼? – Radiodef
班學生實施可比較,通用是學生。當我把它放在頁面上時,我錯過了它。 –
順便說一句,如果'obj'不是'Student'的一個實例,'equals'不應該拋出'ClassCastException',它應該返回false。 – Radiodef