zoukankan      html  css  js  c++  java
  • 增强for循环

    1.定义

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

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

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

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

    2.格式

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

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

     1 Map<String,Integer> score=new HashMap<String,Integer>();
     2         score.put("1", 90);
     3         score.put("2", 80);
     4         score.put("3", 70);
     5         Set<String> keyset=score.keySet();
     6         for(String key : keyset){
     7             Integer value=score.get(key);
     8             System.out.println(key+" : "+value);
     9         }
    10 
    11 //对一个Set类型的集合进行遍历操作,任意输出(无序)。
    12         Set c1=new HashSet();    
    13         c1.add("AAA");
    14         c1.add("BBB");
    15         c1.add("CCC");  
    16         for(String c:c1){
    17             System.out.println(c);
    18         } 

    4.比较

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

     1 import java.util.LinkedList;
     2 import java.util.List;
     3 import org.junit.Test;
     4 public class ForTest {
     5     @Test
     6     public void TestForTime() {                             
     7             List<Integer> list = new LinkedList<Integer>();
     8             for (int i = 0; i < 10000; i++) {
     9                 list.add(1);
    10             }
    11             //普通for循环
    12             long start = System.currentTimeMillis();
    13             for (int i = 0; i < list.size(); i++) {
    14                int result1 = list.get(i);
    15             }
    16             System.out.println("普通循环使用了"+ (System.currentTimeMillis() - start)+"毫秒");
    17             //增强for循环
    18             start = System.currentTimeMillis();
    19             for (int c2 : list) {
    20 
    21                int result2=c2;
    22             }
    23             System.out.println("增强for循环使用了"+ (System.currentTimeMillis() - start)+"毫秒");
    24     }
    25 }

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

  • 相关阅读:
    Oracle创建表空间、创建用户以及授权、查看权限
    Oracle建立表空间和用户
    Oracle创建用户、表空间、导入导出、...命令
    C#中AppDomain.CurrentDomain.BaseDirectory与Application.StartupPath的区别
    maven 工程启动找不到 Spring ContextLoaderListener 的解决办法
    配置整合DWR3.0和Spring2.5使用annotation注解
    jQuery打印
    个项目涉及到的50个Sql语句(整理版)
    编写安卓平台程序的几种方式
    豪总说
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/4713842.html
Copyright © 2011-2022 走看看