[19/03/27-星期三] 容器_Iterator(迭代器)之遍历容器元素(List/Set/Map)&Collections工具类

迭代器为我们提供了统一的遍历容器的方式

1/*2*迭代遍历3*4*/5packagecn.sxt.collection;67importjava.security.KeyStore.Entry;8importjava.util.ArrayList;9importjava.util.HashMap;10importjava.util.HashSet;11importjava.util.Iterator;12importjava.util.List;13importjava.util.Map;14importjava.util.Set;151617publicclass Test_0327_Iterator {18publicstaticvoid main(String[] args) {19//testIteratorList();20//testIteratorSet();21testIteratorMap();222324}2526publicstaticvoid testIteratorList() {//测试迭代器遍历list27 List<String> list=newArrayList<String>();28list.add("A");29list.add("B");30list.add("D3");31list.add("C");32for (Iterator<String> iter = list.iterator(); iter.hasNext();) {33 String temp =iter.next();34 System.out.print(temp +"\t");//输出遍历结果35if (temp.endsWith("3")) {//删除3结尾的字符串36iter.remove();37}38}39System.out.println("\n"+list);40}414243publicstaticvoid testIteratorSet() {//测试迭代器遍历set, 与上边一模一样44 Set<String> set=newHashSet<String>();45set.add("A");46set.add("B");47set.add("B3");48set.add("C");49for (Iterator<String> iter = set.iterator(); iter.hasNext();) {50 String temp =iter.next();51 System.out.print(temp +"\t");//输出遍历结果52}53}5455@SuppressWarnings("unchecked")56publicstaticvoid testIteratorMap() {//测试迭代器遍历Map57 Map<Integer,String> map=newHashMap<Integer,String>();58 map.put(101,"A");59 map.put(104,"D");60 map.put(103,"C");61//不知道哪里错了,心累,就是报错 ,以后解决626768 Set<Integer> ss = map.keySet();//第二种遍历方式69for (Iterator<Integer> iterator = ss.iterator(); iterator.hasNext();) {70 Integer key =iterator.next();71 System.out.println(key +"--"+map.get(key));72}73}74}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwdypw.html