黑马程序员技术交流社区
标题:
代码
[打印本页]
作者:
刘德坤
时间:
2015-10-21 21:36
标题:
代码
package com.itheima;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*
題目:编写一个类,在main方法中定义一个Map对象(采用泛型),加入若干个对象,然后遍历并打印出各元素的key和value。
分析:
1.创建Map对象
2.加入若干对象
3.遍历Map对象
4.打印元素key和value
步骤:
1.Map<String,Integer> map = new HashMap<String,Integer>();
2.map.put("小明", 21);
3.while(it.hasNext()){
Map.Entry<String,Integer> me = it.next();
}
4.System.out.println("key:"+me.getKey()+"------"+"value:"+me.getValue());
*/
public class Test11 {
public static void main(String[] args) {
//创建Map对象
Map<String,Integer> map = new HashMap<String,Integer>();
//加入若干对象
map.put("小明", 21);
map.put("小王", 18);
map.put("小李", 45);
//遍历Map对象
Set<Map.Entry<String,Integer>> set = map.entrySet();
Iterator<Map.Entry<String,Integer>> it = set.iterator();
while(it.hasNext()){
Map.Entry<String,Integer> me = it.next();
//打印元素key和value
System.out.println("key:"+me.getKey()+"------"+"value:"+me.getValue());
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2