您的位置:首页 > 编程语言 > Java开发

java中HashMap简单使用

2016-04-05 16:33 375 查看
public void HashMapDemo(){
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("cn", "中国");
hashMap.put("jp", "日本");
hashMap.put("fr", "法国");

System.out.println(hashMap);
System.out.println("cn:" + hashMap.get("cn"));
System.out.println(hashMap.containsKey("cn"));
System.out.println(hashMap.keySet());
System.out.println(hashMap.isEmpty());
//
hashMap.remove("cn");
System.out.println(hashMap.containsKey("cn"));

//采用Iterator遍历HashMap
Iterator it = hashMap.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
System.out.println("key:" + key);
System.out.println("value:" + hashMap.get(key));
}

//遍历HashMap的另一个方法
Set<Entry<String, String>> sets = hashMap.entrySet();
for(Entry<String, String> entry : sets) {
System.out.print(entry.getKey() + ", ");
System.out.println(entry.getValue());
}
}

输出结果为:

//I/System.out(10809): {cn=中国, jp=日本, fr=法国}
//04-05 16:23:11.702: I/System.out(10809): cn:中国
//04-05 16:23:11.703: I/System.out(10809): true
//04-05 16:23:11.703: I/System.out(10809): [cn, jp, fr]
//04-05 16:23:11.703: I/System.out(10809): false
//04-05 16:23:11.703: I/System.out(10809): false
//04-05 16:23:11.703: I/System.out(10809): key:jp
//04-05 16:23:11.703: I/System.out(10809): value:日本
//04-05 16:23:11.703: I/System.out(10809): key:fr
//04-05 16:23:11.703: I/System.out(10809): value:法国
//04-05 16:23:11.703: I/System.out(10809): jp, 日本
//04-05 16:23:11.703: I/System.out(10809): fr, 法国
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: