通过以下实例来体验Map的具体用法:
通过Map
创建一个Student类
public class Student
{
public String id;
public String name;
public Set<Course> courses;
public String getId () {
return id;
}
public void setId (String id) {
this .id = id;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public Student (String id, String name) {
this .id = id;
this .name = name;
courses=new HashSet<Course>();
}
}
创建一个MapTest测试类
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MapTest
{
public Map<String,Student> mStudentMap;
public Scanner mScanner;
public MapTest ()
{
this .mStudentMap=new HashMap<String,Student>();
mScanner=new Scanner(System.in );
}
public static void main (String[]args)
{
MapTest mapTest=new MapTest();
mapTest.testPut();
mapTest.testKeySet();
mapTest.testRemove();
mapTest.testEntrySet();
mapTest.testModefy();
mapTest.testEntrySet();
}
public void testPut ()
{
int i=0 ;
while (i<3 )
{
System.out .println("请输入学生ID:" );
String ID=mScanner.next();
Student st=mStudentMap.get (ID);
if (st==null )
{
System.out .println("请输入学生姓名:" );
String name=mScanner.next();
Student newStudent=new Student(ID,name);
mStudentMap.put(ID,newStudent);
System.out .println("成功添加学生:" +mStudentMap.get (ID).getName());
i++;
}else
{
System.out .println("该学生ID已被占用" );
continue ;
}
}
}
public void testKeySet ()
{
Set<String> keySet=mStudentMap.keySet();
for (String stuId:keySet
) {
Student st=mStudentMap.get (stuId);
if (st!=null )
{
System.out .println("学生:" +st.getName());
}
}
}
public void testRemove ()
{
while (true )
{
System.out .println("请输入待删除的学生ID:" );
String id=mScanner.next();
Student st=mStudentMap.get (id);
if (st==null )
{
System.out .println("该ID不存在" );
continue ;
}
mStudentMap.remove(id);
System.out .println("成功删除学生:" +st.name);
break ;
}
}
public void testEntrySet ()
{
Set<Map.Entry<String,Student>> entrySet=mStudentMap.entrySet();
for (Map.Entry<String,Student> entry:entrySet)
{
System.out .println("取得键:" +entry.getKey());
System.out .println("对应的值为:" +entry.getValue().getName());
}
}
public void testModefy ()
{
System.out .println("请输入要修改的学生ID:" );
while (true )
{
String stuID=mScanner.next();
Student st=mStudentMap.get (stuID);
if (st==null )
{
System.out .println("该ID不存在!重新输入" );
continue ;
}
System.out .println("当前该学生ID,所对应的学生为:" +st.getName());
System.out .println("请输入新的学生姓名:" );
String name=mScanner.next();
Student student=new Student(stuID,name);
mStudentMap.put(stuID,student);
System.out .println("修改成功!" );
break ;
}
}
}