package Collection;标签:HashMap,students,System,name,2023,println,ID,out From: https://www.cnblogs.com/RUI2022/p/17020426.html
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MapTest {
public Map<String,Student> students;
public MapTest() {
this.students = new HashMap<String,Student>();
}
//测试添加
public void testPut(){
//创建一个scanner类,用于录入学生ID和姓名
Scanner console = new Scanner(System.in);
int i=0;
while (i<3){
System.out.println("请输入学生ID:");
String ID = console.next();
//判定是否被占用
Student st = students.get(ID);
if (st==null){
//提示输入学生姓名
System.out.println("请输入学生姓名:");
String name = console.next();
//创建新的学生对象
Student newstudent = new Student(ID, name);
//通过调用PUT方法,添加ID-学生映射
students.put(ID,newstudent);
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();
//取得students容量大小
System.out.println("总共有:"+students.size()+"个学生");
//通过遍历keyset,取得每一个键,再调用get方法取得每个键对应的value
for (String stuId:keySet) {
Student st = students.get(stuId);
if (st!=null)
System.out.println("学生:"+st.name);
}
}
//测试删除MAP中的映射
public void testRemove(){
Scanner console = new Scanner(System.in);
while (true){
System.out.println("请输入要删除的学生ID:");
String ID = console.next();
//把ID的东西给学生对象,判断是否有对应学生对象
Student st = students.get(ID);
if (st==null){
System.out.println("该ID不存在");
continue;
}
students.remove(ID);
System.out.println("成功删除学生"+st.id+st.name);
break;
}
}
//通过ENTRYSET来遍历
public void testEntrySet(){
Set<Map.Entry<String,Student>> entrySet = students.entrySet();
for (Map.Entry<String,Student>entry:entrySet){
System.out.println("取得键:"+entry.getKey());
System.out.println("对应的值为:"+entry.getValue().id+entry.getValue().name);
}
}
/**
利用put方法修改MAP中的已有映射
*/
public void testModify(){
//提示输入要修改的学生
System.out.println("请输入要修改的学生ID:");
//录入
Scanner console = new Scanner(System.in);
while (true){
String stuID = console.next();
Student student = students.get(stuID);
if (student==null){
System.out.println("该ID不存在,请重新输入");
continue;
}
System.out.println("当前该学生ID,所对应的学生为:"+student.name);
//输入新的姓名
System.out.println("请输入新的学生姓名:");
String name = console.next();
Student newStudent = new Student(stuID,name);
students.put(stuID,newStudent);
System.out.println("修改成功!");
break;
}
}
public static void main(String[] args) {
MapTest mt = new MapTest();
mt.testPut();
mt.testKeySet();
//mt.testRemove();
//mt.testEntrySet();
mt.testModify();
mt.testEntrySet();
}
}