定义一个Map对象,遍历并打印出各元素的key和value

来源:互联网 发布:淘宝客服工作室 编辑:程序博客网 时间:2024/04/28 18:13

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.itheima.bean.Person;

public class Test2 {

/** * 2、编写一个类,在main方法中定义一个Map对象(采用泛型), *    加入若干个对象,然后遍历并打印出各元素的key和value。 */public static void main(String[] args) {    //创建HashMap 集合  泛型为 Person 类    HashMap<Person, String> hm = new HashMap<>();    //向集合中添加数据   key为Person对象   value为字符串    hm.put(new Person("顾雨磊",25), "河北");    hm.put(new Person("周红伟",23), "杭州");    hm.put(new Person("黑马",20), "上海");    hm.put(new Person("程序员",18), "北京");    hm.put(new Person("IT人",1), "中国");    /*第一种方法    遍历并打印出各元素的key和value    hm.keySet()获取key及学生对象*/    System.out.println("...........第一种方法使用hm.keySet()...........");    for (Person personkey : hm.keySet()) {        System.out.println("姓名: "+personkey.getName()+", 年龄: "+personkey.getAge()+", 来自: "+hm.get(personkey));    }    System.out.println("...........第二种方法使用hm.entrySet()...........");    /*第二种方法遍历*/    for (Entry<Person, String> en : hm.entrySet()){        System.out.println("姓名: "+en.getKey().getName()+", 年龄: "+en.getKey().getAge()+", Value: "+en.getValue());    }}

}

0 0
原创粉丝点击