黑马程序员技术交流社区

标题: HashMap存储自定义对象 [打印本页]

作者: 薛灵云    时间: 2015-8-29 21:10
标题: HashMap存储自定义对象
package cn.itcast_02;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
* HashMap存储键和值。并遍历。
* 键:String 学号
* 值:Student (name,age)
*/
public class HashMapDemo2 {
        public static void main(String[] args) {
                // 创建集合对象
                HashMap<String, Student> hm = new HashMap<String, Student>();

                // 创建元素对象
                Student s1 = new Student("李世民", 30);
                Student s2 = new Student("朱元璋", 40);
                Student s3 = new Student("武则天", 50);

                // 添加元素
                hm.put("it001", s1);
                hm.put("it002", s2);
                hm.put("it003", s3);

                // 遍历
                Set<String> set = hm.keySet();
                for (String key : set) {
                        Student value = hm.get(key);
                        System.out.println(key + "***" + value.getName() + "***"
                                        + value.getAge());
                }

                // 遍历2
                Set<Map.Entry<String, Student>> hmSet = hm.entrySet();
                for (Map.Entry<String, Student> me : hmSet) {
                        String key = me.getKey();
                        Student value = me.getValue();
                        System.out.println(key + "***" + value.getName() + "***"
                                        + value.getAge());
                }
        }
}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2