問題已經自我排查解決
@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() {
//本例中讓用戶輸入某個學生的姓名,再去判斷姓名所對應的學生是否包含在這個studentsMap中
//提示輸入學生Id
System.out.println("請輸入要查詢的學生ID:");
Scanner console = new Scanner(System.in);//定義一個Scanner對象
String id = console.next();//取得從鍵盤上輸入的學生id字符串
//在Map中,用containsKey()方法,來判斷是否包含某個Key值
System.out.println("你輸入的學生id為"+id+",在學生映射表中是否存在"+students.containsKey(id));
//判斷如果存在就輸出那個學生的姓名
if(students.containsKey(id))
System.out.println("對應的學生為:"+students.get(id).name);
//提示輸入學生姓名
System.out.println("請輸入要查詢的學生姓名:");
String name = console.next();//從鍵盤上取得輸入的學生姓名字符串
//用containsValue()方法,來判斷是否包含某個Value值
if(students.containsValue(new Student(null,name)))//先創建一個學生對象,id設置為空,姓名設為name的值,
System.out.println("在學生映射表中,確實包含學生:"+name);//暫時先回到student類驗證有沒有調用Value有關的equals方法
else
System.out.println("在學生映射表中不存在該學生!");
}
請輸入學生ID:
1
請輸入學生姓名:
明
成功添加學生:明
請輸入學生ID:
2
請輸入學生姓名:
紅
成功添加學生:紅
請輸入學生ID:
3
請輸入學生姓名:
華
成功添加學生:華
總共有:3個學生
學生:明
學生:紅
學生:華
請輸入要查詢的學生ID:
1
你輸入的學生id為1,在學生映射表中是否存在true
對應的學生為:明
請輸入要查詢的學生姓名:
明
在學生映射表中不存在該學生!
2019-12-11
問題已自我排查解決