第84行代碼為什么es.getValue()為什么調用不了name屬性,代碼見正文
package?com.imooc.Map;
import?java.util.HashMap;
import?java.util.Map;
import?java.util.Map.Entry;
import?java.util.Scanner;
import?java.util.Set;
import?com.imooc.collection.Student;
public?class?MapTest?{
public?Map<String,Student>students;
/*
?*?在構造器中初始化students屬性
?*/
public?MapTest(){
this.students=new?HashMap();
}
/*
?*?添加學生:
?*?首先檢查是否被占用,如果被占用,輸出提示信息
?*?如若沒有,將該學生信息輸入到學生的屬性中,并打印出學生信息
?*/
public?void?TestPut(){
int?i=0;
while(i<3){//此處用while循環更加合適?。。? System.out.println("請輸入學號:");
Scanner?input=new?Scanner(System.in);
String?id=input.next();
Student?newStudent=students.get(id);
if(newStudent==null){
System.out.println("請輸入姓名:");
String?name=input.next();
//創建學生對象
Student?a=new?Student(id,name);
students.put(id,?a);
System.out.println("成功添加學生"+students.get(id).name);
i++;
}else{
System.out.println("您的id已被占用!");
continue;
}??
}
}
public?void?testKeySet(){
//通過keySet方法,返回Map中的所有"鍵"的Set集合
Set<String>?keySet=students.keySet();
//遍歷keySet,取得每個key值,再調用get方法取得每個鍵對應的value
for(String?stuID:keySet){
Student?st=students.get(stuID);
System.out.println(st.name);
}
}
/*
?*?刪除Map中的映射
?*/
public?void?testRemove(){
System.out.println("請輸入要刪除的id:");
while(true){
Scanner?input=new?Scanner(System.in);
String?id=input.next();
Student?st=students.get(id);
if(st==null){
System.out.println("您輸入的id不存在,請重新輸入:");
continue;
}
students.remove(id);
System.out.println("已經成功刪除"+st.name);
break;
}
}
/*
?*?通過entrySet方法遍歷Map
?*/
public?void?testEntrySet(){
//通過entrySet方法返回所有的鍵值對
Set<Entry<String,?Student>>?entrySet=students.entrySet();
for(Entry?es:entrySet){
System.out.println("key值:"+es.getKey());
System.out.println("Value值:"+es.getValue());
}
}
public?static?void?main(String[]?args){
?????????MapTest?mt=new?MapTest();
?????????mt.TestPut();
?????????mt.testKeySet();
?????????mt.testRemove();
?????????mt.testEntrySet();
}
}Student代碼:
package?com.imooc.collection;
import?java.util.HashSet;
import?java.util.Set;
public?class?Student?{
?public?String?id;
?public?String?name;?
?public?Set<Course>?courses;
?
?public?Student(String?id,String?name){
?this.id=id;
?this.name=name;
?this.courses=new?HashSet<Course>();
?
?}
}
2017-02-17
給Entry指定一下泛型
for(Entry<String,?Student>?es:entrySet){ ????System.out.println("key值:"+es.getKey()); ????System.out.println("Value值:"+es.getValue().name);??? }2017-02-17
es.getValue() 得到的是Student對象,用es.getValue().name獲得Student的name屬性。