码迷,mamicode.com
首页 > 其他好文 > 详细

增强for循环

时间:2015-08-08 21:18:13      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

1.定义

当对数组和集合进行遍历时,可以使用增强for循环。增强for循环的效果和iterator相同,其内部是通过调用iteratoer实现的。但是增强for循环存在以下缺点:

1)不能动态地删除集合或数组内容

2)完整的遍历集合或数组,而不能只遍历部分

3)在遍历集合或数组时,不能获取当前元素下标

2.格式

       for(元素类型 i : 数组或集合对象) {

            System.out.println(i);
       }
3.实例

Map<String,Integer> score=new HashMap<String,Integer>();
        score.put("1", 90);
        score.put("2", 80);
        score.put("3", 70);
        Set<String> keyset=score.keySet();
        for(String key : keyset){
            Integer value=score.get(key);
            System.out.println(key+" : "+value);
        }

对一个Set类型的集合进行遍历操作,任意输出(无序)。
        Set c1=new HashSet();    
        c1.add("AAA");
        c1.add("BBB");
        c1.add("CCC"); 
        for(String c:c1){
            System.out.println(c);
        }  

4.比较

集合或数组元素数目较大时,不同遍历方式的时间测试:

import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;


public class ForTest {
    @Test
    public void TestForTime() {                             
            List<Integer> list = new LinkedList<Integer>();
            for (int i = 0; i < 10000; i++) {
                list.add(1);
            }
            //普通for循环
            long start = System.currentTimeMillis();
            for (int i = 0; i < list.size(); i++) {
               int resut = list.get(i);
            }
            System.out.println("普通循环使用了"+ (System.currentTimeMillis() - start)+"毫秒");
            //增强for循环
            start = System.currentTimeMillis();
            for (int c2 : list) {
            }
            System.out.println("增强for循环使用了"+ (System.currentTimeMillis() - start)+"毫秒");
    }
}

技术分享

参考文献:http://www.cnblogs.com/linjiqin/archive/2011/02/10/1950929.html

增强for循环

标签:

原文地址:http://www.cnblogs.com/jfl-xx/p/4713842.html

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