為什么我的equals方法用了也還是返回false 代碼如下
?@Override
?public int hashCode() {
??final int prime = 31;
??int result = 1;
??result = prime * result + ((name == null) ? 0 : name.hashCode());
??return result;
?}
?@Override
?public boolean equals(Object obj) {
??if (this == obj)
???return true;
??if (obj == null)
???return false;
??if (!(obj instanceof Student))
???return false;
??Student other = (Student) obj;
??if (name == null) {
???if (other.name != null)
????return false;
??} else if (!name.equals(other.name))
???return false;
??return true;
?}
public void testContainsKeyOrValue() {
??//提示輸入學生ID
??System.out.println("請輸入要查詢的學生ID");
??Scanner sc=new Scanner(System.in);
??String id=sc.next();
??//用ContainsKey判斷
??System.out.println("您輸入的學生ID為"+id+"在學生映射表中是否存在"
??+students.containsKey(id));
??if(students.containsKey(id)) {
???System.out.println("對應學生為:"+students.get(id).name);
??}
??//提示輸入學生姓名
??System.out.println("請輸入要查詢的學生姓名");
??String name=sc.next();
??//用ContainsValue方法來判斷是否存在輸入的學生姓名
??if(students.containsValue(new Student("null","name"))) {
???System.out.println("映射表中包含學生"+name);
??}else {
???System.out.println("該學生不存在");
??}
?}
2020-04-05
樓上正解
2019-08-29
new Student("null","name")? ?---- >?new Student(null,name)
name加雙引號就是字符串“name”了,不是變量name
2019-08-17
運行以后輸入姓名返回結果還是 ? 該學生不存在