我正在尝试创建一个Linked List dequeue类,它接受头部和后部的节点。我的方法tailRemove()应该只删除双端队列尾部的项目。但是,当我打印它时,它正在打印地址。 toString()方法适用于所有其他方法,所以我不确定我在这里做错了什么。谢谢你的帮助!
public class LinkedDequeue
{
private QueueNode front; //index of current front element
private QueueNode rear; //index of current rear element
private int count; //current # of elements
class QueueNode
{
private Object data;
private QueueNode link;
}
public LinkedDequeue ()
{
front = new QueueNode();
rear = new QueueNode();
count = 0;
}
public void headAdd (Object o)
{
QueueNode temp = new QueueNode();
temp.data = o;
if (isEmpty())
{
front = temp;
rear = front;
front.link = null;
rear.link = null;
}
else
{
temp.link = front;
front = temp;
}
count++;
}
public void tailAdd (Object o)
{
QueueNode temp = new QueueNode();
temp.data = o;
temp.link = null;
if (front == null) front = rear = temp;
else
{
rear.link = temp;
rear = temp;
}
count++;
}
public Object tailPeek()
{
return rear.data;
}
public Object tailRemove()
{
QueueNode temp = new QueueNode ();
QueueNode end = new QueueNode();
if (isEmpty()) return null;
else
{
temp = front;
while (temp.link != rear)
{
temp = temp.link;
}
end = rear;
rear.data = temp.data;
rear.link = null;
count--;
return end;
}
}
public String toString()
{
QueueNode current = front;
StringBuilder elements = new StringBuilder();
while (current != null)
{
elements.append (current.data + "\n");
current = current.link;
}
return elements.toString();
}
public static void main (String [] args)
{
LinkedDequeue list = new LinkedDequeue ();
list.headAdd ("test?");
list.tailAdd("in the middle perhaps");
list.tailAdd ("yikes, does this work?");
System.out.println (list.toString());
System.out.println (list.tailPeek());
System.out.println (list.tailRemove());
}
}
答案 0 :(得分:1)
方法tailRemove()
返回类型为QueueNode
的对象。因此,当您将其传递给System.out.println()
时,它会调用toString()
类的QueueNode
方法。由于您未在toString()
类中提供QueueNode
的自定义实现,因此它会调用Object
类中的默认实现并打印Object的hashCode。
解决方案: 您还需要覆盖QueueNode类中的toString()方法。
答案 1 :(得分:0)
作为Kakarot mentioned,在toString()
课程中创建QueueNode
方法可以解决问题。您正在打印的end
变量没有自定义toString()
方法。
原因是在Java中,默认的toString()
方法每个对象只打印其内存地址。如果你想让它做一些有用的事情,你需要自己覆盖它。