遍历数组和集合可以用增强for语句来实现

 

数组和集合可以用for增强来遍历:

 

              int[] arr = { 1, 2, 3, 4, 5 };

 

              // 旧式方式

              for (int i = 0; i < arr.length; i++)

              {

                     System.out.println(arr[i]);

              }

 

              System.out.println("--------------------------");

 

              // 新式方式,增强的for循环

 

              for (int element : arr)

              {

                     System.out.println(element);

              }

 

              System.out.println("--------------------------");

 

              String[] names = { "hello", "world", "welcome" };

 

              for (String name : names)

              {

                     System.out.println(name);

              }

 

              System.out.println("--------------------------");

 

              int[][] arr2 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

             

              for(int[] row : arr2)

              {

                     for(int element : row)

                     {

                            System.out.println(element);

                     }

              }

             

              System.out.println("--------------------------");

             

              Collection col = new ArrayList();

             

              col.add("one");

              col.add("two");

              col.add("three");

             

              for(String str : col)

              {

                     System.out.println(str);

              }

             

 

你可能感兴趣的:(j2se学习总结)