public class MapTestGetValue {
public static void main(String[] args) {
HashMap hashmap = new HashMap();
hashmap.put("A","关羽");
hashmap.put("B","张飞");
hashmap.put("C","赵云");
hashmap.put("D","马超");
hashmap.put("E","黄忠");
//方法一:
Set set1 =hashmap.keySet(); //获取所有的键,因为键是不能重复是set类型,value是可以重复所以是collection类型
for(Iterator iter = set1.iterator();iter.hasNext(); ){
String key = (String)iter.next();
String value = (String)hashmap.get(key);
System.out.println(key + "=" + value);
}
System.out.println("---------------------分隔------------------------------");
//方法二:
//获取hashmap中所有键和值,存进set类型的变量set
Set set2 =hashmap.entrySet();
for(Iterator iter = set2.iterator(); iter.hasNext(); ){
//Object a = iter.next();
// 因为entrySet是Map.enter类型的,所以不能是Object类型,否则无法调用子类方法所以要向下转型
Map.Entry entry = (Map.Entry) iter.next();
//调用获取键方法getKey()
String key = (String) entry.getKey();
//调用获取值方法getValue();
String value = (String) entry.getValue();
System.out.println(key + "=" + value);
}
}
}
A=关羽
B=张飞
C=赵云
D=马超
E=黄忠
---------------------分隔------------------------------
A=关羽
B=张飞
C=赵云
D=马超
E=黄忠
网友评论