使用for-each循环的三种情况

1.Collection容器类

  如ArrayList类中

1 List<String> list = new ArrayList<String>();
2     list.add("Red");
3     list.add("Yellow");
4     list.add("Blue");
5     for(String element : list){
6         System.out.printf("%s", element);
7     }

2.对Arrays数组的遍历

1 int[] numArray = {1, 2, 3, 4, 5, 6};
2 for(int count = 0; count<numArray.length; count++){
3     System.out.print(numArray[count]);
4 }
5 //for-each
6 for(int element : numArray){
7     System.out.print(element);
8 }

3.实现了接口java.lang.Iterable<T>自行撰写的普通类

1 public void displayCatalog(){
2     if(this.catalog.getNumberOfItems() == 0){
3         stdErr.println("The catalog is empty");
4     }else{
5     for(CatalogItem item : this.catalog){
6         stdOut.println(item.getCode() + " " + item.getTitle() + " "
7                              + (item.isAvailable() ? "(A)" : "(NA)"));
8     }
9 }//从而Catalog类的实例可以放在:右边

 

posted @ 2020-05-09 11:58  小菜在路上  阅读(229)  评论(0编辑  收藏  举报