学生类
package com.lanxi.demo1_3;
public class Student {
private String name;
private String sex;
private int age;
@Override//重写toString方法
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
public Student() {//无参构造方法
super();
}
public Student(String name, String sex, int age) {//有参构造方法
super();
this.name = name;
this.sex = sex;
this.age = age;
}
//getter,setter方法
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public int getAge() {
return age;
}
}
测试类
package com.lanxi.demo1_3;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("请输入学生编号");
Scanner input=new Scanner(System.in);
Integer num=input.nextInt();
Map map=new HashMap();
map.put(1, new Student("张三","男",18));
map.put(2, new Student("李四","男",20));
map.put(3, new Student("小花","女",16));
map.put(4, new Student("大花","女",18));
//遍历
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
Entry en=(Entry)it.next();
//查看输入的学生编号,集合中是否存在
if ((map.containsKey(num))||(num==(Integer)en.getKey())) {
//如果存在,输出“存在”,并输出该学生信息
System.out.println("存在");
System.out.println(map.get(num));
break;
}else{
//如果不存在,则输出“不存在”
System.out.println("不存在");
break; }
}
System.out.println();
System.out.println("移除后遍历");
map.remove(4);
Iterator it1=map.entrySet().iterator();
while(it1.hasNext()){
System.out.println(it1.next());
}
} }
运行截屏