zoukankan      html  css  js  c++  java
  • JAVA学习--集合的遍历

     1 @Test
     2     public void testFor3(){
     3         String[] str = new String[]{"AA","BB","DD"};
     4         for(String s : str){
     5             s =  "MM";//此处的s是新定义的局部变量,其值的修改不会对str本身造成影响。
     6             System.out.println(s);
     7         }        
     8         
     9         for(int i = 0;i < str.length;i++){
    10             System.out.println(str[i]);
    11         }
    12     }
    13     @Test
    14     public void testFor2(){
    15         String[] str = new String[]{"AA","BB","DD"};
    16         for(int i = 0;i < str.length;i++){
    17             str[i] = i + "";
    18         }
    19         
    20         for(int i = 0;i < str.length;i++){
    21             System.out.println(str[i]);
    22         }
    23     }
    24     
    25     //***********************************************
    26     //使用增强for循环实现数组的遍历
    27     @Test
    28     public void testFor1(){
    29         String[] str = new String[]{"AA","BB","DD"};
    30         for(String s:str){
    31             System.out.println(s);
    32         }
    33     }
    34     
    35     //使用增强for循环实现集合的遍历
    36     @Test
    37     public void testFor(){
    38         Collection coll = new ArrayList();
    39         coll.add(123);
    40         coll.add(new String("AA"));
    41         coll.add(new Date());
    42         coll.add("BB");
    43         
    44         for(Object i:coll){
    45             System.out.println(i);
    46         }
    47     }
    48     
    49     //错误的写法
    50     @Test
    51     public void test2(){
    52         Collection coll = new ArrayList();
    53         coll.add(123);
    54         coll.add(new String("AA"));
    55         coll.add(new Date());
    56         coll.add("BB");
    57         coll.add(new Person("MM", 23));
    58         
    59         Iterator i = coll.iterator();
    60         
    61         while((i.next())!= null){
    62             //java.util.NoSuchElementException
    63             System.out.println(i.next());
    64         }
    65     }
    66     //正确的写法:使用迭代器Iterator实现集合的遍历
    67     @Test
    68     public void test1(){
    69         Collection coll = new ArrayList();
    70         coll.add(123);
    71         coll.add(new String("AA"));
    72         coll.add(new Date());
    73         coll.add("BB");
    74         
    75         Iterator i = coll.iterator();
    76         while(i.hasNext()){
    77             System.out.println(i.next());
    78         }
    79     }
  • 相关阅读:
    PHP做ERP, CRM, CMS系统需要注意哪些地方
    java封装小实例
    java中数组的数组问题
    switch语句小练习
    java交换两个变量值a,b的多钟方法
    java中 i = i++ 的结果
    每日java基础知识(01)
    计算机存储负数以及int转byte时-128的出现
    python RSA 加密
    CentOS 7 安装 建立svn仓库 远程连接
  • 原文地址:https://www.cnblogs.com/zhangfan94/p/4263325.html
Copyright © 2011-2022 走看看