码迷,mamicode.com
首页 > 编程语言 > 详细

java-for循环遍历数组

时间:2018-08-28 23:45:47      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:static   tostring   int   div   数据类型   ati   code   UNC   方便   

格式:
 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());
          }
        }

 

java-for循环遍历数组

标签:static   tostring   int   div   数据类型   ati   code   UNC   方便   

原文地址:https://www.cnblogs.com/zimo-bwl1029-s/p/9551319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!