• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
火磷
Memory will fade,but not notes.
博客园    首页    新随笔    联系   管理    订阅  订阅
增强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

posted on 2015-08-08 20:37  火磷  阅读(1254)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3