00079_增强for循环

1、格式

 1 /*
 2       *  JDK1.5新特性,增强for循环
 3       *  JDK1.5版本后,出现新的接口 java.lang.Iterable
 4       *    Collection开始继承Iterable
 5       *    Iterable作用,实现增强for循环
 6       *    
 7       *    格式:
 8       *      for( 数据类型  变量名 : 数组或者集合 ){
 9       *         sop(变量);
10       *      }
11       */
12      public static void function_1(){
13         //for对于对象数组遍历的时候,能否调用对象的方法呢
14         String[] str = {"abc","love","Java"};
15         for(String s : str){
16           System.out.println(s.length());
17         }
18       }

2、实现for循环,遍历数组

 1 /*
 2        *  实现for循环,遍历数组
 3        *  好处: 代码少了,方便对容器遍历
 4        *  弊端: 没有索引,不能操作容器里面的元素
 5        */
 6       public static void function(){
 7         int[] arr = {3,1,9,0};
 8         for(int i : arr){
 9           System.out.println(i+1);
10         }
11         System.out.println(arr[0]);
12       }

3、增强for循环遍历集合

 1 /*
 2          *  增强for循环遍历集合
 3          *  存储自定义Person类型
 4          */
 5         public static void function_2(){
 6           ArrayList<Person> array = new ArrayList<Person>();
 7           array.add(new Person("a",20));
 8           array.add(new Person("b",10));
 9           for(Person p : array){
10             System.out.println(p);// System.out.println(p.toString());
11           }
12         }
原文地址:https://www.cnblogs.com/gzdlh/p/8093631.html