java-for循环遍历数组

格式:
 for( 数据类型 变量名 : 数组或者集合 ){
 sop(变量);
 }

public static void function_1(){
        //for对于对象数组遍历的时候,能否调用对象的方法呢
        String[] str = {"abc","itcast","cn"};
        for(String s : str){
          System.out.println(s.length());
        }
      }

实现for循环,遍历数组
* 好处: 代码少了,方便对容器遍历
* 弊端: 没有索引,不能操作容器里面的元素

public static void function(){
        int[] arr = {3,1,9,0};
        for(int i : arr){
          System.out.println(i+1);
        }
        System.out.println(arr[0]);
      }

增强for循环遍历集合

public static void function_2(){
          ArrayList<Person> array = new ArrayList<Person>();
          array.add(new Person("a",20));
          array.add(new Person("b",10));
          for(Person p : array){
            System.out.println(p);// System.out.println(p.toString());
          }
        }

 

posted @ 2018-08-28 22:20  进阶的憨狗  阅读(3124)  评论(0编辑  收藏  举报