【java编程】foreach支持集合、Collection、Iterable遍历原因分析
1、Collection、AbstractCollection、Iterable关系
分析:
1、foreach循环支持对Iterable类(实现了Iterable接口)的遍历,该结论在本blog第3节得到论证;2、Collection接口继承Iterable接口,foreach支持对实现了Collection接口实例类(ArrayList,LinkedList,HashSet,TreeSet,LinkedHashSet)的遍历,该结论已在《【Java编程】Foreach对数组、Collection对象、Iterable对象》得到论证;3、Collection接口继承Iterable接口,AbstractCollection抽象类实现了Collection接口,foreach支持使用继承AbstractCollection类创建Collection实现类的遍历,该结论在本blog第2点得到论证;2、使用继承AbstractCollection类来创建一个Collection的实现(该Collection实现类支持foreach遍历)你要实现一个不是Collection的外部类时,由于让它去实现Collection接口可能非常困难,此时使用AbstractCollection就会变得相当吸引人;AbstractCollection提供了Collection的默认实现,使得你可以创建AbstractCollection的子类,而其中没有不必要的代码重复,不过继承AbstractCollection来实现Collection需要强制实现iterator()和size(),以便提供AbstractCollection没有实现但是AbstractCollection中的其他方法会使用的方法;
package com.andieguo.iterabledemo;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Iterator;public class ReversibleArrayList<T> extends ArrayList<T> {private static final long serialVersionUID = 2843552489593809340L;public ReversibleArrayList(Collection<T> c){super(c);}/** * 注意区别new Iterable<T>方法与new Iterator<T>()方法 * 使用Iterable能够适用于foreach。使用Iterator能适用于while循环迭代 * @return */public Iterable<T> reversed(){return new Iterable<T>(){@Overridepublic Iterator<T> iterator() {// TODO Auto-generated method stubreturn new Iterator<T>() {int current = size()-1;//size()是父类ArrayList里的方法@Overridepublic boolean hasNext() {// TODO Auto-generated method stubreturn current > -1;}@Overridepublic T next() {// TODO Auto-generated method stubreturn get(current--);}@Overridepublic void remove() {// TODO Auto-generated method stubthrow new UnsupportedOperationException();}};}};}public static void main(String[] args) {ReversibleArrayList<String> ral = new ReversibleArrayList<String>(Arrays.asList("one two three four five six".split(" ")));for(String str:ral){System.out.print(str+" ");}System.out.println();for(String str:ral.reversed()){System.out.print(str+" ");}}}5、参考文献:《Java编程思想(美)Bruce Eckel著 陈昊鹏 译 第4版》