1、Map遍历key的两种方法
1 Map<String, String> map = new HashMap(); 2 map.put("username", "mv");
(1)第一种方法:
1 Set<String> keySet = map.keySet();
2 Iterator<String> it = keySet.iterator();
3 while (it.hasNext()) {
4 String key = it.next();
5 String value = map.get(key);
6 System.out.println(key);
7 }
(2)第二种方法:
1 Set<Map.Entry<String, String>> entrySet = map.entrySet();
2 Iterator<Map.Entry<String, String>> it = entrySet.iterator();// Map.Entry嵌套类
3 while (it.hasNext()) {
4 Map.Entry<String, String> me = it.next();
5 String key = me.getKey();
6 String value = me.getValue();
7 System.out.println(key + ": " + value);
8 }
注:第二种方法中:Map.Entry<String, String>解释:
1 interface MyMap{
2 public static interface MyEntry{// 内部接口
3 void get();
4 }
5 }
6 class MyDemo implements MyMap.MyEntry{
7 public void get() {}
8 }
2、Map常用的子类:
|--HashTable:内部结构是哈希表,是同步的。不允许null作为键,null作为值。
|--Properties:用来存储键值对型的信息,可以和IO技术相结合。
|--HashMap:内部结构是哈希表,不是同步的。允许null作为键,null作为值。
|--TreeMap:内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。