從頭認識java-9.13 foreach與迭代器
這一章節我們來說一下foreach與Iterator。
1.例子:
package com.ray.ch09;import java.util.ArrayList;public class Test {public static void showItems(Iterable iterator) {for (Integer item : iterator) {System.out.println(item);}}public static void main(String[] args) {ArrayList list = new ArrayList();for (int i = 0; i < 10; i++) {list.add(i);}showItems(list);}}
上面的例子是不是很熟悉,但是也不盡相同?
因為上面我們只是沿用了foreach,但是增加了Iterable介面這個東西。
在foreach的實現裡面,只要實現了Iterable介面的容器,都可以使用foreach,因此, 儘管foreach一般使用在數組裡面,但是在大部分容器裡面也是可以使用的。
我們將上一章節的代碼修改一下,形成新的代碼:
package com.ray.ch09;import java.util.Iterator;public class Test {public static void showItems(Iterator iterator) {while (iterator.hasNext()) {Person person = iterator.next();System.out.print(person.getId() + );}}public static void showItems(Iterable iterator) {for (Person person : iterator) {System.out.println(person.getId());}}public static void main(String[] args) {PersonList personList = new PersonList();showItems(personList.iterator());showItems(personList);}}class Person {private int id = 0;public int getId() {return id;}public void setId(int id) {this.id = id;}}class PersonList implements Iterable {private Person[] persons = new Person[10];public PersonList() {for (int i = 0; i < persons.length; i++) {Person person = new Person();person.setId(i);persons[i] = person;}}public Iterator iterator() {return new Iterator() {private int index = 0;@Overridepublic boolean hasNext() {return index < persons.length;}@Overridepublic Person next() {return persons[index++];}@Overridepublic void remove() {// 以後會展開實現}};}}
代碼基本差不多,只不過在遍曆到時候不再是使用Iterable,而是只能使用foreach。
注意:上面把數組和實現Iterable介面的類放在一起說,但是如果你當數組實現了Iterable介面,那就有問題了,看下面的代碼。
package com.ray.ch09;import java.util.Arrays;public class Test {public static void showItems(Iterable iterator) {for (Integer item : iterator) {System.out.println(item);}}public static void main(String[] args) {Integer[] array = new Integer[10];for (int i = 0; i < 10; i++) {array[i] = i;}// showItems(array);//errorshowItems(Arrays.asList(array));}}
如果把數字當成參數傳過去,拋異常,只有在數組轉成list後,才能使用。
當然, 如果我們接受的參數直接就是數組,那麼,又會不一樣。
package com.ray.ch09;public class Test {public static void showItems(Integer[] items) {for (Integer item : items) {System.out.println(item);}}public static void main(String[] args) {Integer[] array = new Integer[10];for (int i = 0; i < 10; i++) {array[i] = i;}showItems(array);}}
總結:這一章節主要講述了foreach與Iterable之間的關係。