package entity; public class Student { private String name;//学员姓名 private String sex;//学员性别 public Student(){ } public Student(String name,String sex){ this.name = name; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
package test; import java.util.HashMap; import java.util.Map; import entity.Student; public class HashMapDemo { public static void main(String[] args) { //1.创建学员对象 Student student1 = new Student("哪吒","男"); Student student2 = new Student("木吒","男"); Student student3 = new Student("莉莉","女"); //2.创建保存“键-值对" 的集合对象 Map students = new HashMap(); //3.把英文名称与学员对象按照“键- 值对”的方式存储在HashMap中 students.put("Naza",student1); students.put("Muza",student2); students.put("Lili",student3); //4.打印键集 System.out.println("键集:"+students.keySet()); //5.打印值集 System.out.println("值集:"+students.values()); //6.打印键-值对集合 System.out.println("键-值对集合:"+students); String key = "Jack"; //7.判断是否存在“Jack”这个键 if(students.containsKey(key)){ Student student = (Student)students.get(key); System.out.println(key+"对应的学员姓名是:"+student.getName()+";性别是:"+student.getSex()); } } }