package com.imooc.collection;
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 newStudent = new Student(ID, name);
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();
System.out.println("总共有 : " + students.size() + "个学生");
for(String stuID : keySet) {
Student st = Student.get(stuID);
if (st != null) {
System.out.println("学生 : " + st.name);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MapTest mt = new MapTest();
mt.testPut();
mt.testKeySet();
}
}
null代表空,集合中没有该ID-学生映射,所以可以添加学生=-=
nall不是空吗
package com.imooc.collection;
import java.util.HashSet;
import java.util.Set;
public class Student {
public String id;
public String name;
public Set<Course> courses;
public Student(String iD2, String name2) {
// TODO Auto-generated constructor stub
}
public static Student get(String stuID) {
// TODO Auto-generated method stub
return null;
}
public void Student(String id,String name) {
this.id = id;
this.name = name;
this.courses = new HashSet<Course>();
}
}
代码没贴全