《数据结构与算法分析-java语言描述》3.16题
题目:提供ListIterator的另一种方式是提供带有声明 Iterator<AnyType> reverseIterator(); 的表,它返回一个Iterator,并被初始化至最后一项,其中next和hasNext被实现成与迭代器向表的前端(而不是向后)推进一致。然后你可以通过使用程序
Iterator<Character> ritr = L .reverseIterator();
while (ritr.hasNext())
System.out.println(ritr.next());
反向打印Test16 L。用这种思路实现 ArrayListReverseIterator 类,让 reverseIterator 返回一个新构造的 ArrayListReverseIterator。
问题:其他的都实现了,现在想通过程序代码打印结果,可是没有输出,我的代码如下:
package Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Test16<AnyType> implements Iterator<AnyType> {
public static void main(String[] args) {
Test16 L = new Test16<>();
Iterator<Character> ritr = L .reverseIterator();
while (ritr.hasNext()) {
System.out.println(ritr.next());
}
}
private static final int DEFAULT_CAPACITY = 10;
private int theSize = 10;
private static char[] theItems = {'a','b','c','d','e','f','g','h','i','j'};
public Test16() {
doClear();
}
public void clear(){
doClear();
}
private void doClear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
public void trimToSize(){
ensureCapacity(size());
}
public char get(int idx){
if (idx<0 || idx>=size())
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}
public char set(int idx, char newVal) {
if (idx<0 || idx>=size())
throw new ArrayIndexOutOfBoundsException();
char old = theItems[idx];
theItems[idx] = newVal;
return old;
}
public void ensureCapacity(int newCapacity) {
if(newCapacity < theSize)
return;
char[] old = theItems;
theItems = new char[newCapacity];
for (int i = 0; i < size(); i++) {
theItems[i] = old[i];
}
}
public boolean add(char x) {
add(size(),x);
return true;
}
public void add(int idx,char x) {
if (theItems.length == size())
ensureCapacity(size()*2+1);
for (int i = theSize; i > idx; i++) {
theItems[i] = theItems[i-1];
}
theItems[idx] = x;
theSize++;
}
public char remove(int idx) {
char removedItem = theItems[idx];
for (int i = idx; i < size()-1; i++) {
theItems[i] = theItems[i+1];
}
theSize--;
return removedItem;
}
Iterator<Character> reverseIterator(){
return new ArrayListReverseIterator();
}
private class ArrayListReverseIterator implements java.util.Iterator<Character>{
private int current = size()-1;
public boolean hasNext() {
return current>0;
}
public Character next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
return theItems[--current];
}
public void remove() {
Test16.this.remove(--current);
}
}
@Override
public boolean hasNext() {
if (size()>0) {
return true;
}
return false;
}
@Override
public AnyType next() {
return null;
}
}
请各位大神帮帮忙!谢谢