1)对list和set集合的迭代 1》通过iterator迭代 Iterator<Integer> it = set.iterator(); while (it.hasNext()) { Integer key = it.next(); System.out.println(key + "\t"); } 2》通过forEach循环 for (String name : list) { System.out.print(name + ‘\t‘); } System.out.println(""); 2)对Map集合迭代 1》通过keySet()方法 Set<Integer> set = map.keySet(); Iterator<Integer> it = set.iterator(); while (it.hasNext()) { Integer key = it.next(); String value = map.get(key); System.out.println(key + " - " + value); } 2》通过entrySet()方法 Set<Entry<Integer, String>> set = map.entrySet(); Iterator<Entry<Integer, String>> it = set.iterator(); while (it.hasNext()) { Entry<Integer, String> en = it.next(); Integer key = en.getKey(); String value = en.getValue(); System.out.println(key + "< - >" + value); } 五】迭代细节:【重点】 在迭代集合时候,一定要动态通知Iterator,而不要动态通知List集合,应选用ListIterator. eg: System.out.println("list前长度:" + list.size());//3 ListIterator<String> it = list.listIterator(); while(it.hasNext()){ String key = it.next(); System.out.print(key+‘\t‘);//jack marry sisi //动态通知迭代器,加入了新元素,从而迭代器自动通知list集合 it.add("qq"); } System.out.println("\nlist后长度:"+list.size());//6 it = list.listIterator(); while(it.hasNext()){ String key = it.next(); System.out.print(key+‘\t‘);//jack qq marry qq sisi qq } System.out.println("\nlist后长度:"+list.size());//6
时间: 2024-10-14 03:07:50