package com.imooc.collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class MapTest {
/*
* 承装学生类型对象
*/
public Map<String, Student> students;
/*
* 在构造方法中初始化students属性
*/
public MapTest() {
this.students = new HashMap<>();
}
/*
* 测试添加方法
*/
public void testPut() {
Scanner in = new Scanner(System.in);
for(int i = 0; i < 3; ) {
System.out.println("请输入学生id");
String id = in.next();
//判断是否被占用
Student stu = this.students.get(id);
if(stu == null) {
System.out.println("请输入学生姓名:");
String name = in.next();
Student stuNew = new Student(id, name);
this.students.put(id, stuNew);
System.out.println("成功添加学生:" + this.students.get(id).name);
++i;
} else {
System.out.println("该学生id已被占用");
// continue;
}
}
//为什么这边关闭Scanner会出现异常?
// in.close();
}
/*
* 测试key set 方法
*/
public void testKeySet() {
Set<String> keySet = this.students.keySet();
System.out.println("总共有:" + this.students.size() + "个学生。");
for (String string : keySet) {
Student stu = this.students.get(string);
if(stu != null) {
System.out.println("学生:" + stu.name);
}
}
}
/*
* 测试删除map中的映射
*/
public void testRemove() {
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("请输入要删除的学生id");
//取消45行的注释,为什么这边会出现异常?NoSuchElementException
String id = in.next();
//判断该id是否有对象的学生对象
Student stu = this.students.get(id);
if(id == null) {
System.out.println("该id不存在");
continue;
}
this.students.remove(id);
System.out.println("成功删除学生:" + stu.name);
break;
}
in.close();
}
/*
* 通过entry set遍历
*/
public void testEntrySet() {
Set<Entry<String, Student>> entrySet = this.students.entrySet();
for (Entry<String, Student> entry : entrySet) {
System.out.println("取得键:" + entry.getKey());
System.out.println("对应的值为:" + entry.getValue().name);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MapTest mt =new MapTest();
mt.testPut();
mt.testKeySet();
mt.testRemove();
mt.testEntrySet();
}
}