hashmap的嵌套,存储一个自定义类
hashmap的嵌套,存储一个自定义类
/*
* hashmap的嵌套,存储一个自定义类
*
*分析:
* 1.创建一个hashmap,且它的键和值的其中一个也是hashmap
* 2.创建两个hashmap,它的键 是自定义类Student
* 3.创建Student对象,并分别向第二步的两个hashmap添加
* 4.分两种方法遍历输出
*/
自定义类:
public class Student { private String name; private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } }
hashmap类:
import java.util.Collection; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; /** * hashmap的嵌套 * @author ma * */ public class HashMapDemo6 { /* * hashmap的嵌套,存储一个自定义类 * *分析: * 1.创建一个hashmap,且它的键和值的其中一个也是hashmap * 2.创建两个hashmap,它的键 是自定义类Student * 3.创建Student对象,并分别向第二步的两个hashmap添加 * 4.分两种方法遍历输出 */ public static void main(String[] args) { //声明一个嵌套的hashmap对象hmhm HashMap<String, HashMap<Student, String>> hmhm = new HashMap<String, HashMap<Student,String>>(); //声明一个hashmap对象hm1 HashMap<Student, String> hm1 = new HashMap<Student, String>(); //声明两个学生对象 Student s1 = new Student("张三",1); Student s2 = new Student("李四",2); //把对象放入hm1 hm1.put(s1, "1"); hm1.put(s2, "2"); //声明一个hashmap对象hm2 HashMap<Student, String> hm2 = new HashMap<Student, String>(); //声明两个学生对象 Student s3 = new Student("赵大",3); Student s4 = new Student("王二",4); //把对象放入hm2 hm1.put(s3, "3"); hm1.put(s4, "4"); //把hm1和hm2放入hmhm hmhm.put("1", hm1); hmhm.put("2", hm2); //遍历输出1 Set<Entry<String, HashMap<Student, String>>> set = hmhm.entrySet(); for (Entry<String, HashMap<Student, String>> entry : set) { Set<Entry<Student, String>> entry1 = entry.getValue().entrySet(); for (Entry<Student, String> entry2 : entry1) { System.out.println(entry2); } } System.out.println("-------------------------------------------------"); //遍历输出2 Collection<HashMap<Student, String>> collection = hmhm.values(); for (HashMap<Student, String> hashMap : collection) { for(Student s : hashMap.keySet()){ System.out.println(s); } } } }
输出结果:
Student [name=李四, age=2]=2
Student [name=王二, age=4]=4
Student [name=赵大, age=3]=3
Student [name=张三, age=1]=1
-------------------------------------------------
Student [name=李四, age=2]
Student [name=王二, age=4]
Student [name=赵大, age=3]
Student [name=张三, age=1]