1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| package com.collection;
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set;
public class MapPutStudent {
public Map<String,Student> students; public MapPutStudent() { this.students = new HashMap<String,Student>(); }
public void testPut() { final int ADD_NUMS = 3; int i=0; while(i<ADD_NUMS) { System.out.println("请输入学生ID:"); Scanner input = new Scanner(System.in); String sid = input.next(); if(students.get(sid) == null) { System.out.println("请输入学生姓名:"); String name = input.next(); Student stuObj = new Student(sid,name); students.put(sid, stuObj); i++; }else { System.out.println("您输入的id已经存在了"); continue; } } }
public void testKeySet() { Set<String> keys = students.keySet(); System.out.println("成功添加"+ keys.size() +"个学生"); for(String key:keys) { Student st = this.students.get(key); System.out.println("学生:" + st.name); } } public static void main(String[] args) { MapPutStudent mp = new MapPutStudent(); mp.testPut(); mp.testKeySet(); } }
|