【问题标题】:How do I return a value of a Node type?如何返回 Node 类型的值?
【发布时间】: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&lt;T&gt; 没有 val 成员。您希望如何访问它?
  • 那我如何获取那个节点的值呢?我可以转换为 T 并返回顶部吗?
  • 那个节点的值你的意思是data成员?

标签: java generics types nodes


【解决方案1】:

datanext 设为私有并添加一个getter

public class Node<T> {
    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() {
        return this.data;
    }

    public Node<T> getNext() {
        return this.next;
    }

    public String toString() {
        return "" + this.data;
    }
}

用途:top.getData();

【讨论】:

  • 谢谢,我完全误解了我的课程结构。我所做的和你所做的都是有道理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多