Java数组、集合的三种遍历方式(包懂)

1 for循环

for(int i = 0;i<arr.length;i++){
    System.out.print(arr[i]+" ");
}

2 foreach循环,这种方式结构简单,可以简化代码

for(int i:arr){
    System.out.print(arr[i]+" ");
}

3 迭代器遍历
对于数组而言,就没必要转换为集合类的数据类型,代码反而冗杂。前面两种对于数组集合均适用
迭代器对List的遍历

List list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
Iterator iterator = list.iterator();
while(iterator.hasNext()){
      System.out.print(iterator.next() +" ");
}

输出结果为:1 2 3

猜你喜欢

转载自www.cnblogs.com/wwgsdh/p/10419750.html