接口 Iterable<T>
public interface Iterable<T>
实现这个接口允许对象成为"foreach"语句的目标
----------------------------------------------------------------------------------
由于Java中数据容器众多,而对数据容器的操作在很多时候都具有极大的共性,于是Java采用了迭代器为各种容器提供公共的操作接口。使用Java的迭代器iterator可以使得对容器的遍历操作完全与其底层相隔离,可以到达极好的解耦效果。
public interface Iterable<T> {
/**
* Returns an iterator over a set of elements of type T.
*
* @return an Iterator.
*/
Iterator<T> iterator();
}
Collection接口拓展了接口Iterable,根据以上的对Iterable接口的定义可以发现,其要求实现其的类都提供一个返回迭代器Iterator<T>对象的方法。
迭代器Iterator<T>接口的的定义为:
package java.util;
/**
* An iterator over a collection. {@code Iterator} takes the place of
* {@link Enumeration} in the Java Collections Framework. Iterators
* differ from enumerations in two ways:
*
* <ul>
* <li> Iterators allow the caller to remove elements from the
* underlying collection during the iteration with well-defined
* semantics.
* <li> Method names have been improved.
* </ul>
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <E> the type of elements returned by this iterator
*
* @author Josh Bloch
* @see Collection
* @see ListIterator
* @see Iterable
* @since 1.2
*/
public interface Iterator<E> {
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
*
* @return {@code true} if the iteration has more elements
*/
boolean hasNext();
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration
* @throws NoSuchElementException if the iteration has no more elements
*/
E next();
/**
* Removes from the underlying collection the last element returned
* by this iterator (optional operation). This method can be called
* only once per call to {@link #next}. The behavior of an iterator
* is unspecified if the underlying collection is modified while the
* iteration is in progress in any way other than by calling this
* method.
*
* @throws UnsupportedOperationException if the {@code remove}
* operation is not supported by this iterator
*
* @throws IllegalStateException if the {@code next} method has not
* yet been called, or the {@code remove} method has already
* been called after the last call to the {@code next}
* method
*/
void remove();
}
从以上的定义中可以发现,似乎Iterable()接口和Iterator()接口完全一致,没有任何区别。可以发现这又是一个支持程序多样化的巧妙设计,充分的支持了多态和解耦。
由于所有的Collection类型的对象都被强制要求implements Iterable 接口,故任何Collection对象都要能返回一个能遍历其的迭代器Iterator。如果直接 implement iterator接口, Collection会直接要求具有hasNext()等方法。但是这种方法不具备多态性,即设定好了该如何执行hasNext()等操作,而且程序会显得十分的臃肿和复杂。但是如果采用实施Iterable()接口和返回Iterator对象的方式,则会全然的不同,只要能够返回Iterator对象,完全可以自己的需要进行遍历方式上的自由定义。(即针对同一个接口,在其实现类中提供多样、不同的方法)。
-------------------------------------------------------------------------------------------------
自定定义一个Person类实现Iterable接口:
package cn.wangyu.itearator;
import java.util.Iterator;
/**
* Person继承了Iterable接口,则Person可以使用JDK1.5新特性的foreach
*/
public class Person implements Iterable<Person> {
private String name;
private int age;
private Person[] persons;
@Override
public Iterator<Person> iterator() {
return new PersonIterator();
}
/**
* PersonIterator是私有内部类,实现了Iterator<E>接口的类
*
* @author JiangMinyan
*
*/
private class PersonIterator implements Iterator<Person>{
private int index = 0;//索引
@Override
public boolean hasNext() {
return index != persons.length;
}
@Override
public Person next() {
return persons[index++];
}
@Override
public void remove() {
}
}
public Person(int size){
persons = new Person[size];
for (int i = 0; i < size; i++) {
persons[i] = new Person(""+i, i);
}
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
//Main Method
public static void main(String[] args) {
Person p = new Person(20);
//----> 可以使用foreach <----//
// for(Person person : p.persons){
// System.out.println(person);
// }
Iterator<Person> iterator = p.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}