本帖最后由 李万海 于 2013-3-28 18:45 编辑
下面是部分遍历集合元素的代码。- //利用迭代器进行遍历
- public static void work(Map<String, Student> map) {
- Collection<Student> c = map.values();
- Iterator it = c.iterator();
- for (; it.hasNext();) {
- System.out.println(it.next());
- }
- }
- //利用keyset进行遍历
- public static void workByKeySet(Map<String, Student> map) {
- Set<String> key = map.keySet();
- for (Iterator it = key.iterator(); it.hasNext();) {
- String s = (String) it.next();
- System.out.println(map.get(s));
- }
- }
- //利用entrySet进行遍历
- public static void workByEntry(Map<String, Student> map) {
- Set<Map.Entry<String, Student>> set = map.entrySet();
- for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) {
- Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next();
- System.out.println(entry.getKey() + "--->" + entry.getValue());
- }
- }
- }
复制代码 这三种方法在遍历集合时,他们的优缺点是什么?哪种方式更适合在实际开发中应用?为什么?
如果用高级for循环来遍历的话,又有什么区别呢?
|