Java中的可比实现

时间:2014-03-09 15:22:32

标签: java generics comparable

我是Java的新手,并尝试实现扩展GeneralList接口的MyLinkedList,我想使用类似的Node接口来保持我的列表排序, 当我尝试创建一个头节点时,它给了我错误

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

//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...

1 个答案:

答案 0 :(得分:6)

您的班级SLL2<T>也应该对T的可比性有所限制。像那样:

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