java - Java中的可比实现

标签 java generics comparable

我是 Java 的新手,正在尝试实现扩展 GeneralList 接口(interface)的 MyLinkedList,我想为我的节点使用可比较的接口(interface)来保持我的列表排序, 当我尝试创建头节点时出现错误

请在以下代码下方找到错误信息

//List interface

public interface GeneralList<T> 
{
    public boolean addNode(T elem);
    public boolean deleteNode(T elem);
    public T containsNode(T elem);
    public void printSll();

} 

//ListImplementation

public class SLL2<T> implements GeneralList<T> 
{   
    private static class Node<T extends Comparable<T>> 
    {
        public T data;
        public Node<T> next;

        public Node() 
        {
            data = null;
            next = null;
        }
    }   

    public SLL2()
    {
        head = null;        
    }

    /* 1. Error while creating a head referance*/
    private Node<T> head;  

    @Override
    public boolean addNode(T elem) 
    {
        Node<T> tmp = new Node<T>();
        tmp.data = elem;

        if(head == null)
        {
            head = temp;
                        return true;
        }
        else
        {
              for(Node<T> cur = head; cur.next != null ; cur= cur.next) 
          {
                    /* iterate and add the node */
                    if(temp.elem.comparTo(cur.elem)) 
                    {
                    }

                }
           }
}

1. I am not able to create the head node with the declaration private Node<T> head;

It is giving error "Bound mismatch: The type T is not a valid substitute for the bounded parameter <T extends Comparable<T>> of the type SLL2<T>.Node<T>"

Please help me to resolve this error...

最佳答案

你的类(class) SLL2<T>还应该对 T 的可比性有约束.像那样:

public class SLL2<T extends Comparable<T>> implements GeneralList<T> {
    // ...

关于java - Java中的可比实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22284051/

相关文章:

c# - 泛型方法可以使用逆变/协变类型吗?

Java 将特定类的列表添加到 java.lang.Object 的列表与 java 8 流一起工作 - 为什么?

Java 和类似的

java - 在 Java 中使用泛型保证协变返回类型

java - 在 Java 中使用比较器比较对象属性

java - 马尔可夫链的比较器和 HashMap

java - 在 Java 中是否可以根据某个变量从两个不同的类继承一个类?

java - APDU读文件java卡程序

java - Java中两个同步块(synchronized block)的区别

java - CouchDB 中的全文搜索