map集合存储实体类--遍历
java源码示例展示:
package map; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * 使用linkedhashmap 效果最好 * 存储学生对象,还要输出 使用 遍历输出 * @author superdrew */ public class TestMapStudent { public static void main(String[] args) { //创建 存储stu的 map key 是 int id value 是具体的每一个学生 Map<Integer,Student> stuMap = new LinkedHashMap<Integer,Student>(); //创建学生对象 Student stu1 = new Student(1001, "Drew", 89, 21); Student stu2 = new Student(2002, "SuperDrew", 99, 20); Student stu3 = new Student(3003, "Lily", 100, 25); Student stu4 = new Student(4004, "Mark", 78, 22); Student stu5 = new Student(5005, "Bob", 88, 21); //把学生对象放入 到 map集合 stuMap.put(stu1.getId(), stu1); stuMap.put(stu2.getId(), stu2); stuMap.put(stu3.getId(), stu3); stuMap.put(stu4.getId(), stu4); stuMap.put(stu5.getId(), stu5); //根据输入的具体学号 返回一个具体的学生信息 @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.println("请输入要查找的学号:"); int id = sc.nextInt(); Student stuObject = stuMap.get(id); System.out.println(stuObject); //遍历map集合输出---错误提示:map集合的三种遍历输出方式,请看我的上一篇blogs。 /*for(int i=1;i<=stuMap.size();i++){ System.out.println(stuMap.get(i)); }*/ /*小结:输出全部为NULL,说明遍历map集合的时候不能简单的使用for i遍历。*/ //获取 stuMap所有的key System.out.println("所有的学生信息如下:"); Set<Integer> stuSet = stuMap.keySet(); for(int stuId:stuSet){ System.out.println(stuMap.get(stuId)); } } }
实体类Student.java:
1 package map; 2 /** 3 * 学生类 4 * @author superdrew 5 * 6 */ 7 public class Student { 8 private int id; 9 private String name; 10 private double score; 11 private int age; 12 13 public int getId() { 14 return id; 15 } 16 public void setId(int id) { 17 this.id = id; 18 } 19 public String getName() { 20 return name; 21 } 22 public void setName(String name) { 23 this.name = name; 24 } 25 public double getScore() { 26 return score; 27 } 28 public void setScore(double score) { 29 this.score = score; 30 } 31 public int getAge() { 32 return age; 33 } 34 public void setAge(int age) { 35 this.age = age; 36 } 37 38 public Student(int id, String name, double score, int age) { 39 super(); 40 this.id = id; 41 this.name = name; 42 this.score = score; 43 this.age = age; 44 } 45 @Override 46 public String toString() { 47 return "Student [id=" + id + ", name=" + name + ", score=" + score + ", age=" + age + "]"; 48 } 49 }
结果展示: