如何使用Comparable比较链表中的通用节点? [英] How to compare generic nodes in a linked list using Comparable?

查看:98
本文介绍了如何使用Comparable比较链表中的通用节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用链接列表实现一个排序列表。我的节点类看起来像这样

I am implementing a sorted list using linked lists. My node class looks like this

public class Node<E>{
    E elem;
    Node<E> next, previous;
}

在排序列表类中,我有add方法,我需要比较泛型对象基于它们的compareTo()方法的实现,但是我得到这个语法错误
方法compareTo(E)对于E类型是未定义的。我试过在Node中实现compareTo方法,但是我不能调用任何对象的方法,因为E是泛型类型。
这是添加(E elem)方法的未完成主体。

In the sorted list class I have the add method, where I need to compare generic objects based on their implementation of compareTo() methods, but I get this syntax error "The method compareTo(E) is undefined for type E". I have tried implemnting the compareTo method in Node, but then I can't call any of object's methods, because E is generic type. Here is the non-finished body of add(E elem) method.

public void add(E elem) 
{

        Node<E> temp = new Node<E>();
        temp.elem = elem;

        if( isEmpty() ) {           
            temp.next = head;
            head.previous = temp;
            head = temp;
            counter++; 
        }else{
            for(Node<E> cur = head; cur.next != null ; cur= cur.next) {
                **if(temp.elem.comparTo(cur.elem)) {**
                    //do the sort;

                }/*else{
                    cur.previous = temp;
                }*/             
            }
            //else insert at the end

        }
}

以下是对象实现compareTo方法之一

Here is one of the object implemnting compareTo method

public class Patient implements Comparable<Patient>{
    public int compareTo(Patient that)
    {
        return (this.getPriority() <= that.getPriority() ? 1 : 0 );
    }
}


推荐答案

E to Comparable:

Bound E to Comparable:

public class Node<E extends Comparable<E>>{
    E elem;
    Node<E> next, previous;
}

现在可以编译。

这篇关于如何使用Comparable比较链表中的通用节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆