1Map.entrySet()方法,什么意思?
entrySet实现了Set接口,里面存放的是键值对。一个K对应一个V。
2 遍历map的一种方法。
代码1:
Map map=···; Set<Map.Entry<String, String>> entryseSet=map.entrySet(); for (Map.Entry<String, String> entry:entryseSet) { System.out.println(entry.getKey()+","+entry.getValue()); }
通过getKey()得到K,getValue得到V。
代码2:
Map<String, List<Record>> listRecord = ···; for (Entry<String, List<Record>> e : listRecord.entrySet()) { String tbName = e.getKey(); List<Record> reList = e.getValue();
}
3Set是什么?和List的关系
Set是集合的意思,是同种对象的集合。 <String>说明这种对象都是String类型的对象。 Set本身是接口,所以需要实现,可以这样定义: Set<String> set = new HashSet<String>(); String s1 = "hello"; String s2 = "world"; set.add(s1); set.add(s2); |
List和Set都是接口。他们各自有自己的实现类,有无顺序的实现类,也有有顺序的实现类。 最大的不同就是List是可以重复的。而Set是不能重复的。 List适合经常追加数据,插入,删除数据。但随即取数效率比较低。 Set适合经常地随即储存,插入,删除。但是在遍历时效率比较低。 |
5Set、Entry和Map的关系
一个Entry,就是一个键值对,即Map中的某一个成员。
一个Map,就是一个Set,即一个键值对数组(即一个List,包含多个Entry)。
Set和Entry,一般在Map遍历的时候,才会用到,平时很少用。