先貼代碼
package com.tsubasa.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class ReversibleArrayList<T> extends ArrayList<T>{ public ReversibleArrayList(Collection<T> c){ super(c) ; } public Iterable<T> reversed(){ return new Iterable<T>(){ @Override public Iterator<T> iterator() { return new Iterator<T>(){ int current = size() -1 ; @Override public boolean hasNext() { return current > -1 ; } @Override public T next() { return get(current--); } @Override public void remove() { throw new UnsupportedOperationException() ; } } ; } } ; } public static void main(String[] args) { ReversibleArrayList<String> list = new ReversibleArrayList<String>( Arrays.asList("to be or not to be it is a question".split(" "))) ; for(String str : list){ System.out.print(str + " "); } System.out.println(); for(String str :list.reversed()){ System.out.print(str + " "); } } }
運行結果:
to be or not to be it is a question
question a is it be to not or be to
上面這種解決方案使用了所謂的適配器方法,適配器部分來自於設計模式,因為我們這里使用foreach遍歷list,所以我們必須提供滿足foreach的接口。
因為我們的ArrayList已經實現了Iterable接口,所以下面有兩個選擇來實現倒序輸出:
1.覆蓋ArrayList原有的iterator方法
2.自己在生產一個iterator接口。
通過上面的代碼,顯然這里我們選擇了第二種方法。