标签:
异常简介(key值不可重复)
案例: package hpu.edu.cn.Admin; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class MapTest { /** * @param args */ public Map<String, Student> students; public MapTest(){ this.students = 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 = students.get(ID); if(st == null){ System.out.println("请输入学生姓名:"); String name = console.next(); Student newSt = new Student(ID,name); students.put(ID, newSt); System.out.println("成功添加学生:" + students.get(ID).name); i++; }else{ System.out.println("该学生ID已被占用!!"); continue; } } } public void testKeySet(){ Set<String> keySet = students.keySet(); System.out.println("总共有:" + students.size() + "个学生!!"); for (String stuId:keySet) { Student st = students.get(stuId); if(st != null){ System.out.println("学生:" + st.name); } } } public void testRemove(){ Scanner console = new Scanner(System.in); while(true){ System.out.println("请输入要删除学生的ID:"); String ID = console.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(){ Set<Entry<String,Student>> entrySet = students.entrySet(); for(Entry<String,Student> entry:entrySet){ System.out.println("取得键:" + entry.getKey()); System.out.println("对应的值为:" + entry.getValue().name); } } 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 newSt = new Student(stuID,name); students.put(stuID,newSt); System.out.println("修改成功!!"); break; } } public static void main(String[] args) { // TODO Auto-generated method stub MapTest mt = new MapTest(); mt.testPut(); mt.testKeySet(); mt.testRemove(); mt.testEntrySet(); } }
标签:
原文地址:http://blog.csdn.net/wojiaohuangyu/article/details/50855890