【发布时间】:2019-09-07 18:22:00
【问题描述】:
我在 toString() 方法中有一个 for-each 循环,它应该遍历通用 FIFO 队列中的元素(使用双向链表数据结构实现)并将队列中的项目连接到字符串 a 上,该字符串返回到 enqueue() 打印字符串,这是我的队列及其在 enqueue 调用后的内容的表示。我的问题是,为什么 for-each 根本没有被执行/输入?
我尝试插入 System.out.print("Hi");在 for-each 里面,它没有打印出来。所以我假设某些代码块阻碍了它正确执行。
// FIFOQueue is implemented using the structure double linked list (DLL)
// Generic, iterable
import java.util.Iterator;
import java.util.*;
public class FIFOQueueDLL<Item> implements Iterable<Item>{
private Node first;
private Node last;
private int length = 0;
// is the queue empty?
public boolean isEmpty(){
return length == 0;
}
private class Node{
Item item;
Node next;
Node previous;
}
// add an item
public void enqueue(Item n){
Node newnode = new Node();
newnode.item = n;
if(isEmpty()){
last = newnode;
} else {
first.previous = newnode;
}
newnode.next = first;
first = newnode;
length++;
System.out.println(this);
}
// remove and return the least recently added item
public Item dequeue(){
if(isEmpty()){
throw new NoSuchElementException();
}
Node t = last;
if(first == last){
first = null;
} else {
last.previous.next = null;
}
last = last.previous;
t.previous = null;
length--;
System.out.println(this.toString(););
return t.item;
}
public String toString(){
String a = "123";
for(Item item : this){
a = a + item;
}
return a;
}
public Iterator<Item> iterator(){
return new FIFOIterator();
}
private class FIFOIterator implements Iterator<Item>{
// Declare attribute
Node curr;
// Set attribute of node curr
public FIFOIterator(){
Node curr = first;
curr.item = first.item;
curr.next = first.next;
}
//private int i = length;
public boolean hasNext(){
return curr != null;
}
public Item next(){
Item a = curr.item;
curr = curr.next;
return a;
}
}
public static void main(String[] args){
FIFOQueueDLL<Character> c = new FIFOQueueDLL<Character>();
char b = 'b';
c.enqueue(b);
c.enqueue(b);
}
}
Expected output: 123b
123bb
Actual output: 123
123
【问题讨论】:
-
你能展示你的班级吗?它是否实现
Iterable?你的方法enqueue是做什么的?你完全省略了有趣的部分 -
this.iterator().hasNext()返回false而你永远不会进入循环 -
@GhostCat 如果我想分享整个程序,我应该编辑我的帖子还是将其粘贴到粘贴箱中并在评论部分分享?
-
您不需要整个程序,只需要minimal reproducible example。如前所述:这里重要的是:如何实现迭代器方法 next() 和 hasNext()。
-
@GhostCat 你好,我现在编辑了帖子以包含实现 Iterable 的类和实现 Iterator 的类。我会很感激任何帮助
标签: java generics iterator queue doubly-linked-list