方法一
用迭代器hasPrevious方法,缺點需要循環兩次
注意,迭代器的游標開始指向第一個元素,必須先將迭代器運行到最后一個元素,再往前才能反向輸出。
否則將沒有任何輸出
ArrayList ar = new ArrayList(Arrays.asList(1, 2, 3,
4, 5, 6, 7, 8));
ar.trimToSize();
Iterator iterator = ar.iterator();
ListIterator it = ar.listIterator();
while (it.hasNext()) {
Integer i = it.next();
System.out.println(i.intValue());
}
while (it.hasPrevious()) {
Integer i = it.previous();
System.out.println(i.intValue());
}
方法二
實現一個反向迭代器
下面代碼來自thinking in java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class ReversibleArrayList extends ArrayList {
public ReversibleArrayList(Collection c) {
super(c);
}
public Iterable reversed() {
return new Iterable() {
public Iterator iterator() {
return new Iterator() {
int current = size() - 1;
public boolean hasNext() {
return current > -1;
}
public T next() {
return get(current--);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
測試代碼
public static void main(String[] args) throws IOException {
ReversibleArrayListral=new ReversibleArrayList(
Arrays.asList("To be or not to be".split(" ")));
for(String s:ral)
System.out.print(s+" ");
System.out.println();
for(String s:ral.reversed())
System.out.print(s+" ");
}