1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import java.util.HashMap; import java.util.Iterator; public class HashMapTest { public static void main(String[] args) { System.out.println("----HashMap----"); // 在 HashMap 中的对象是无序的 HashMap<String, Integer> hm = new HashMap<String, Integer>(); hm.put("a",11); hm.put("b",22); hm.put("c",33); // 测试是否包含关键字"a" System.out.println(hm.containsKey("a")); System.out.println(hm.containsKey("d")); System.out.println(hm.get("a")); System.out.println(hm.entrySet()); // 遍历 Iterator<?> it = hm.entrySet().iterator(); while(it.hasNext()) { System.out.println(it.next()); } // Set keySet() 返回关键字的集合 it = hm.keySet().iterator(); while(it.hasNext()) { System.out.println(hm.get(it.next())); } // Collection values() 返回值的集合 it = hm.values().iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }
|