如何在Java中编写方法签名“T实现Comparable <t>”</t>

时间:2012-07-26 12:01:24

标签: java generics comparable

我的insert方法应该有哪些签名?我正在与仿制药斗争。在某种程度上,我想要Comparable<T>T,我尝试过<Comparable<T> extends T>

public class Node<T> {

    private Comparable<T> value;

    public Node(Comparable<T> val) {
        this.value = val;
    }

    // WRONG signature - compareTo need an argument of type T
    public void insert(Comparable<T> val) {
        if(value.compareTo(val) > 0) {
            new Node<T>(val);
        }
    }

    public static void main(String[] args) {
        Integer i4 = new Integer(4);
        Integer i7 = new Integer(7);

        Node<Integer> n4 = new Node<>(i4);
        n4.insert(i7);
    }
}

1 个答案:

答案 0 :(得分:7)

不确定您要实现的目标,但是您是否应该在课程声明中包含该内容?

public static class Node<T extends Comparable<T>> { //HERE

    private T value;

    public Node(T val) {
        this.value = val;
    }

    public void insert(T val) {
        if (value.compareTo(val) > 0) {
            new Node<T>(val);
        }
    }
}

注意:最好使用<T extends Comparable<? super T>>代替<T extends Comparable<T>>