import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Iterator; public class Main { static PrintWriter cout = new PrintWriter(System.out, true); static Scanner cin = new Scanner(System.in); public static void main (String[] args){ HashMap<String, String> map = new HashMap<String, String>(); map.put("China", "中国"); map.put("China", "zhongguo"); //键已存在,将"中国"覆盖 map.put("Japen", "日本"); map.put("American", "美国"); //输出map容器的大小 cout.println(map.size()); //以数组形式,打印map容器 cout.println(map.entrySet()); //以数组形式打印键 cout.println(map.keySet()); //以数组形式打印值 cout.println(map.values()); //判断是否存在某个键 if(map.containsKey("China")) { cout.println("find success"); } else { cout.println("losing finding"); } //判断是否存在某个值 if(map.containsValue("中国")) { cout.println("find success"); } else { cout.println("losing finding"); } //按键寻值 cout.println(map.get("China")); //不存在则返回null cout.println(map.get("china")); //map容器遍历 //方法一: for(Map.Entry<String, String> entry : map.entrySet()) { cout.println("Key="+entry.getKey()+", Value="+entry.getValue()); } //方法二:增加了按键寻值,效率低 for(String s : map.keySet()) { cout.println("Key="+s+", Value="+map.get(s)); } //方法三:最快 for(Iterator<Map.Entry<String, String>> it=map.entrySet().iterator();it.hasNext();) { Map.Entry<String, String> entry = it.next(); System.out.println("key:"+entry.getKey()+", value:"+entry.getValue()); } //将容器清空 map.clear(); //判断容器是否为空 cout.println(map.isEmpty()); } }