我试图实现以下实现Iterable的deque:
public class Dequeue<E> implements Iterable<E> {
protected List<E> deque;
public Dequeue() {
this.deque = new ArrayList<>();
}
public void insertFirst( E elem ) {
this.deque.add( 0, elem );
}
public void insertLast( E elem ) {
this.deque.add( elem );
}
public E removeFirst() {
return (this.deque.isEmpty()) ? null : this.deque.remove(0);
}
public E removeLast() {
return (this.deque.isEmpty()) ? null : this.deque.remove( this.deque.size() - 1 );
}
public E examineFirst() {
return this.deque.get(0);
}
public E examineLast() {
return this.deque.get( this.deque.size() - 1 );
}
@Override
public Iterator<E> iterator() {
return new DequeIterator<>(false);
}
public Iterator<E> iterator( boolean isDesc ) {
return new DequeIterator<>(isDesc);
}
public class DequeIterator<E> implements Iterator<E> {
private int index;
private boolean isDesc;
public DequeIterator( boolean isdesc ) {
this.index = isdesc ? deque.size() - 1 : 0;
}
@Override
public boolean hasNext() {
return isDesc ? index > 0 : index < deque.size();
}
@Override
public E next() {
this.index = (isDesc) ? index-- : index++;
return (E) deque.get(index);
}
@Override
public void remove() {
deque.remove(index);
}
}
}
但是,如果我尝试使用以下代码对其进行测试,则会进入无限循环。发生了什么?编译器不会返回任何类型的错误,我也不知道我是否正确地执行了Iterator类。
List<Integer> result = new ArrayList<>();
Dequeue<Integer> deque = new Dequeue<>();
deque.insertLast( new Integer(1) );
deque.insertLast( new Integer(2) );
for( Integer i : deque ) {
System.out.println(i);
}
答案 0 :(得分:1)
您的代码中确实存在3
个错误:
deque
,而是遍历无用的列表result
isDesc
的构造函数中成员变量DequeIterator
的值。DequeIterator#next()
中的索引,你会影响post增量/减量的值,这将以相同的索引结束,所以无限循环,直接使用结果将增量/减量作为索引。以下是修正后的代码:
Dequeue<Integer> deque = new Dequeue<>();
deque.insertLast(1);
deque.insertLast(2);
for( Integer i : deque ) {
System.out.println(i);
}
课程Dequeue.DequeIterator
public class DequeIterator<E> implements Iterator<E> {
...
private boolean isDesc;
public DequeIterator( boolean isdesc ) {
...
this.isDesc = isdesc;
}
...
@Override
public E next() {
return (E) deque.get(isDesc ? index-- : index++);
}
...
}