牛骨文教育服务平台(让学习变的简单)
博文笔记

增强for循环详解

创建时间:2016-12-19 投稿人: 浏览次数:6574

•for循环中的循环条件中的变量只求一次值!具体看最后的图片

•foreach语句是java5新增,在遍历数组、集合的时候,foreach拥有不错的性能。

•foreach是for语句的简化,但是foreach并不能替代for循环。可以这么说,任何foreach都能改写为for循环,但是反之则行不通。

•foreach不是java中的关键字。foreach的循环对象一般是一个集合,List、ArrayList、LinkedList、Vector、数组等。

•foreach的格式:

for(元素类型T 每次循环元素的名称O : 循环对象){

        //对O进行操作

    }

一、常见使用方式。

1. foreach遍历数组。

?
1 2 3 4 5 6 7 8 9 10 11 12 /**  * 描述:  * Created by ascend on 2016/7/8.  */ public class Client {   public static void main(String[] args) {     String[] names = {"beibei", "jingjing"};     for (String name : names) {       System.out.println(name);     }   } }

2.foreach遍历List。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /**  * 描述:  * Created by ascend on 2016/7/8.  */ public class Client {     public static void main(String[] args) {     List<String> list = new ArrayList();     list.add("a");     list.add("b");     list.add("c");     for(String str : list){       System.out.println(str);     }   } }

二、局限性。

foreach虽然能遍历数组或者集合,但是只能用来遍历,无法在遍历的过程中对数组或者集合进行修改,而for循环可以在遍历的过程中对源数组或者集合进行修改。

1.数组

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /**  * 描述:  * Created by ascend on 2016/7/8.  */ public class Client {     public static void main(String[] args) {     String[] names = {"beibei", "jingjing"
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。