遍歷數組和集合可以用增強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<String> col = new ArrayList<String>();

             

              col.add("one");

              col.add("two");

              col.add("three");

             

              for(String str : col)

              {

                     System.out.println(str);

              }

             

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章