【发布时间】:2017-12-05 15:48:53
【问题描述】:
我正在尝试使用 Stack 类来完成 peek 方法。我正在尝试返回顶部元素的值。
public class stack<T> implements StackInt<T>
{
Node<T> root;
public boolean isEmpty()
{
Node<T> top = root;
if( top == null)
{
return true;
}
return false;
}
public T peek() throws EmptyStackException
{
Node<T> top = root;
if(isEmpty())
{
throw new EmptyStackException("stack underflow");
}
return top.val;
}
}
当我编译它给我一个错误:
stack.java:34: error: cannot find symbol
return top.val;
^
symbol: variable val
location: variable top of type Node<T>
where T is a type-variable:
T extends Object declared in class stack
这是 Node 类:
public class Node<T>
{
T data;
Node<T> next;
public Node( T data, Node<T> next )
{
this.data = data;
this.next = next;
}
public String toString()
{
return "" + this.data;
}
}
我的语法有什么错误?我正在尝试使用节点来创建 peek/push/pop 方法。但是我必须在我的代码中使用泛型类型 T。
谢谢
【问题讨论】:
-
正如错误试图告诉你的那样,你试图返回一个不存在的字段。
-
我们需要查看 Node 源代码。请参阅minimal reproducible example。
-
Node<T>没有val成员。您希望如何访问它? -
那我如何获取那个节点的值呢?我可以转换为 T 并返回顶部吗?
-
那个节点的值你的意思是
data成员?