Iterable是一个接口,它只有一个方法iterator(),要求返回一个Iterator。
package java.lang;
public interface Iterable<T>
{
Iterator<T> iterator();
}
而Iterator本身也是个接口,它有hasNext()、next()、remove三个方法。
package java.util;
public interface Iterator<T>
{
boolean hasNext();
T next();
void remove(); //optional
}
一般的实现为:
import java.util.*;
public class StringArray implements Iterable<String>
{
private String[] words;
public StringArray()
{
words = "This is the default sentence".split(" ");
}
public StringArray(String sentence)
{
words = sentence.split(" ");
}
public Iterator<String> iterator()
{
return new Iterator<String>()
{
private int index = 0;
public boolean hasNext()
{
return index <= words.length - 1;
}
public String next()
{
return words[index++];
}
public void remove()
{
//we do not implement it here
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args)
{
StringArray sa = new StringArray("Hello World");
for (String s : sa)
System.out.println(s);
}
}
//output:
/*
Hello
World
*/
目前有这么一个问题,如果一个类想要有不同的Iterator怎么办?实现Iterable接口是只能产生一个Iterator的。我们很容易地想到可以使用多个方法来返回不同的Iterator (或者Iterable),而不是去实现Iterable接口。不过这么一来还可以使用foreach语句么?还是可以的,如下:
import java.util.*;
public class ReverseStringArray
{
private String[] words;
public ReverseStringArray()
{
words = "This is the default sentence".split(" ");
}
public ReverseStringArray(String sentence)
{
words = sentence.split(" ");
}
public Iterable<String> reverseIterable()
{
return new Iterable<String>()
{
public Iterator<String> iterator()
{
return new Iterator<String>()
{
private int index = words.length - 1;
public boolean hasNext()
{
return index >= 0;
}
public String next()
{
return words[index--];
}
public void remove()
{
//we do not implement it here
throw new UnsupportedOperationException();
}
};
}
};
}
public static void main(String[] args)
{
ReverseStringArray rsa = new ReverseStringArray("Hello World");
for (String s : rsa.reverseIterable())
System.out.println(s);
}
}
//output:
/*
World
Hello
*/
由此可见,foreach语句接收的只是Iterable接口,所以,只要类可以提供一个Iterable接口,那么它就能被foreach处理。对实现了Iterable的类而言,可以理解为是一个向上转型(upcast),即for (String s : sa)其实是for (String s : (Iterable)sa);对没有实现Iterable的类而言,需要显式提供一个Iterable给foreach语句,如for (String s : rsa.ReverseIterable())。