public class MapTest {
public Map<String ,Student> student;
public MapTest(){
this.student = new HashMap<String ,Student>();
}
public void testPut(){
Scanner console = new Scanner(System.in);
int i = 0;
while(i<3){
System.out.println("请输入学生ID");
String ID = console.next();
Student st = student.get(ID);
if(st == null){
System.out.println("请输入学生姓名");
String name = console.next();
Student newStudent = new Student(ID,name);
student.put(ID,newStudent);
System.out.println("成功添加学生:"+student.get(ID).name);
i++;
}else {
System.out.println("该学生的ID已被占用");
continue;
}
}
}
public void testKeySet(){
//返回所有key的集合
Set<String> keySet=student.keySet();
for (String stuId:keySet) {
Student st = student.get(stuId);
if(st!=null){
System.out.println("学生"+st.name);
}
}
}
public void testRemove(){
System.out.println("请输入要删除的学生ID");
Scanner console = new Scanner(System.in);
while (true) {
String ID = console.next();
Student st = student.get(ID);
if (st == null) {
System.out.println("该ID不存在");
continue;
}
student.remove(ID);
System.out.println("成功删除学生:"+st.name);
break;
}
}
public void testEntrySet(){
//返回所有键值对的集合
Set<Map.Entry<String,Student>> entrySet = student.entrySet();
for (Map.Entry<String,Student> entry:entrySet) {
System.out.println("取得键为:"+entry.getKey());
System.out.println("对应的值为:"+entry.getValue().name);
}
}
public static void main(String[] args) {
MapTest mt =new MapTest();
mt.testPut();
mt.testKeySet();
mt.testRemove();
mt.testEntrySet();
}
}