使用 Iterator 迭代器的方式遍历数据,即使只是取数据,不改变原来的集合,遍历完 Iterator 这个对象,这个对象就没了!就没了!就没了!
而不是像 List 这类集合,只取不改变原集合,是可以一直重复去取值的,真的是不知道的话,很容易中坑啊
public static void main(String[] args) { String cons[] = {"1","2","3","4","5"}; List<String> lists = new ArrayList<>(); for(int i=0;i<cons.length;i++) { lists.add(new String(cons[i])); } for (String list : lists) { System.out.print(list+" "); } System.out.println(" ==============="); for (String list : lists) { System.out.print(list+" "); } System.out.println(" ==下面是迭代器的遍历=="); Iterator<String> iter = lists.iterator(); while(iter.hasNext()) { System.out.print(iter.next()+" "); } System.out.println(" ==============="); while(iter.hasNext()) { System.out.print(iter.next()+" "); } }
//遍历结果: 1 2 3 4 5 =============== 1 2 3 4 5 ==下面是迭代器的遍历== 1 2 3 4 5 ===============