java - 如何实现扩展 Comparable 的列表列表?

标签 java generics linked-list generic-list comparable

我尝试制作一个通用链表。

此链表的节点使用 <T extends Comparable <T>> 。但是当我使用

LList<LList<Integer>> linkedlist = new LList<LList<Integer>>();

创建新实例时出现错误:

Multiple markers at this line
- Bound mismatch: The type LList<Integer> is not a valid substitute
   for the bounded parameter <T extends Comparable<T>> of the type LList<T>
- Bound mismatch: The type LList<Integer> is not a valid substitute
   for the bounded parameter <T extends Comparable<T>> of the type

如何解决这个问题?

<小时/> 节点类:

public class Node <T extends Comparable <T>> {

// Members:
public T data;
public Node <T> next;
// Methods:
public Node () {
    data =null;
    next = null;
}
public Node (T data) {
    this.data = data;
    next = null;
}
}

LList类:

public class LList <T extends Comparable <T>> {

// Members:
public Node <T> head;
// Methods:
public LList () {
    head = null;
}

// Add node.
public void addNode (T data) {
    if (head == null) {
        head = new Node <T> (data);
        return;
    }
    Node <T> newNode = new Node <T> (data);
    Node <T> tempNode = head;
    while (tempNode.next != null) tempNode = tempNode.next;
    tempNode.next = newNode;
}

// Show linked list.
public void showLLForInteger () {
    if (head == null) return;
    Node <T> tempNode = head;
    while (tempNode != null) {
        System.out.print(String.format("%-6d", tempNode.data));
        tempNode = tempNode.next;
    }
    System.out.println();
}
}

最佳答案

  1. 您为什么需要 T extends Comparable<T> ?您似乎没有在任何地方使用它。

  2. 既然您需要 T extends Comparable<T> ,这意味着列表的参数必须与其自身进行比较。 LList<LList<Integer>>不起作用,因为 LList<Integer>与自身不可比较(它不扩展 Comparable<LList<Integer>> )。你确定你不只是想要 LList<Integer>

关于java - 如何实现扩展 Comparable 的列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901375/

相关文章:

java - Robolectric 和 Mockito 监视 Android Activity

java - 将第一个节点插入到空双向链表中[如何]

c - 双链表中的冒泡排序导致尝试从 NULL 读取

java - 数组连接和类型转换

c - 使用 fscanf() 用文件信息填充 C 中的链表,它不是在读取文件的第一行吗?

java - 使用链表实现队列时出现 NullPointer 异常

java - 如何在应用程序关闭后取消闹钟

java - 查询以检查时间戳

java - Doxygen 将 Java 泛型方法视为包保护

Java 泛型方法基础知识(反射)