我只是尝试在通用ArrayList类中创建自己的Iterator。通常,Iterator接口包括next(),hasNext(),remove()方法。我想添加一些额外的方法。但是在测试这个迭代器时,我不能使用额外的方法。我甚至看不到他们。
注意:MyListIterator类是ArrayList类中的内部类。
private class MyListIterator implements Iterator<E>{
private int j=0;
private boolean removableNext = false;
private boolean removablePrev= false;
public boolean hasNext() { return j < size; } // size is field of outer instance
public E next() throws NoSuchElementException {
if (j == size) throw new NoSuchElementException("No next element");
removableNext = true; // this element can subsequently be removed
removablePrev=false;
return data[j++]; // post-increment j, so it is ready for future call to next
}
public boolean hasPrevious(){
return (j > -1) ;
}
public E previous(){
if(j==-1) throw new NoSuchElementException("No previous element");
removablePrev= true;
removableNext=false;
return data[j--];
}
public void remove(){
if (!removableNext && !removablePrev) throw new IllegalStateException("nothing to remove");
if(removableNext){
ArrayList.this.remove(j-1);
j--;
removableNext = false;
}
if(removablePrev){
ArrayList.this.remove(j+1);
j++;
removablePrev = false;
}
}
public void set(E e){
if (!removableNext && !removablePrev) throw new IllegalStateException("nothing to remove");
if(removableNext){
ArrayList.this.set(j-1,e);
j--;
removableNext = false;
}
if(removablePrev){
ArrayList.this.set(j+1,e);
j++;
removablePrev = false;
}
}
}
测试时我只看到从Iterator实现的remove(),next(),hasNext()方法。
测试类是:
import java.util.Iterator;
public class DriverIterator {
public static void main(String[]args){
ArrayList<Integer> list = new ArrayList<>();
list.add(0, 1);
list.add(0, 2);
list.add(0, 3);
list.add(0, 4);
list.add(0, 5);
System.out.println(list.toString());
Iterator<Integer> iter = list.myListIterator();
}
}
ArrayList类属于我,如果有必要,我也可以共享它。