黑马程序员_java增强for循环自动装箱与拆箱

------- android培训java培训、期待与您交流! ----------

 

增强for循环的限制条件:当遍历集合或者是数组的时候,如果需要访问集合或者是数组的下标,那么最好使用普通的遍历形式,此时增强for循环时候非常不变。

代码演示
package test2;

public class Test3 {
        public static void main(String[] args) {
            int [] arr = new int[]{1,2,3,4,5};
            for(int i = 0;i<arr.length;i++ )
            {
                System.out.println(arr[i]);
            }
           
            System.out.println("------------------");
           
            for(int i:arr)
            {
                System.out.println(i);
            }
        }
}


public class Test3 {
        public static void main(String[] args) {
            people[] str = new people[3];
            str[0]=new people("luochuang");
            str[1]=new people("luochuang1");
            str[2]=new people("luochuang2");

           
                for(people str1:str)
                {
                    System.out.println(str1.name);
                }
        }

}

class people
{
    String name ;
    people(String name )
    {
        this.name=name;
    }
}

自动装箱与拆箱

代码示例:
import java.util.ArrayList;

public class Test4 {
    public static void main(String[] args) {
        ArrayList<Integer> str = new ArrayList<Integer>();
        str.add(1);
        str.add(2+6);
        str.add(3);
        
        for(Integer str1:str)
        {
            System.out.println(str1);
        }
    }
}
注意类型的转化。

------- android培训java培训、期待与您交流! ----------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值