定义方法时Java中的泛型抛出错误

我正在学习Java泛型。为此,我尝试了一个简单的LinkedList。

pip install theia

但是当所有方法确实存在于Node类中时,我都会收到此错误。我在做什么错?

class Node {
  private int age;
  private String name;
  private Node next;

  public Node(int age,String name) {
    this.age = age;
    this.name = name;
    this.next = null;
  }

  public int getage() {
    return this.age;
  }

  public String getName() {
    return this.name;
  }

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

  public void setNext(Node next) {
    this.next = next;
  }
}

class LinkedList<T> {
  private T head;
  private T current;

  public LinkedList() {
    head = null;
    current = null;
  }

  public void append(T x) {
    if (head == null) {
      head = x;
      current = x;
    }
    else {
      current.setNext(x);
      current = x;
    }
  }

  public T getat(int index) {
    T ptr = head;
    for(int i = 0; i < index; i++) {
      ptr = ptr.getNext();
    }
    return ptr;
  }
}

class Main {
  public static void main(String[] args) {
    LinkedList<Node> list = new LinkedList<Node>();
    list.append(new Node(39,"John"));
    list.append(new Node(43,"Josh"));
    Node x = list.getat(1);
    System.out.println(String.format("%d,%s",x.getage(),x.getName()));
  }
}
la_zhanghui 回答:定义方法时Java中的泛型抛出错误

如果<T extends Comparable<T>>的类型为to_filter,则不能在const data = [[1,2],[2,3],[3,4],[4,5],[5,6]] const to_filter = [2,5] const output = data.filter( subArray => subArray.some(x => to_filter.includes(x)) ) console.log(output)上调用current类的方法(例如T),因为{实例化Node时,{1}}可以被任何类替代。

您的setNext()类不应是current的泛型类型参数。 T应该始终由LinkedList组成。每个Node中存储的数据类型应该是通用类型。

LinkedList

LinkedList应该包含Node个节点:

Node
,

编译器无法理解T类型。您已使用t.setNext(),但是除非实际使用,否则它在T定义中不存在。我可能在这里听起来有点困惑,但是尝试一下:

创建一个具有setNext和getNext方法的接口Contract。 实现Node扩展到接口之上。 Node implements Contract。 在链接列表中,将泛型更改为T extends Contract

,

对于任何给定的通用hasNext没有T,因此代码无法编译

您必须确保LinkedList仅包含Node类或其子类型

class LinkedList<T extends Node>

但是请注意:T与存储在节点中的泛型不相同,因此看起来更好

class LinkedList<T> {
    Node<T> head;
,

private T current;是通用类型,您正在对其调用setNextgetNextT怎么知道它总是有这些方法?这就是它无法正常工作的原因。

因此,您需要确保您的通用类型T知道它具有setNextgetNext方法。

因此,解决方法是:

T extends NodeAbstract在类定义中,其中NodeAbstract是声明这些方法签名的接口。现在,这可以确保T获得的所有内容始终具有这两种方法。

,

您必须制作Node<T>LinkedList<Node>

public void append(T x) { // Here x is of Type T
if (head == null) {
  head = x;
  current = x; //Assigning x to current,current is also of Type T
}
else {
  current.setNext(x); // T.setNext is not defined! Because T can be a String/Integer/whatever. They do not have setNext method
  current = x;
}
}
本文链接:https://www.f2er.com/3161845.html

大家都在问