如何编写实现可比方法签名“T ”在Java中?(How to write a method s

2019-09-20 05:51发布

我应该有我的签名什么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);
    }
}

Answer 1:

不知道你想什么来实现,但你不应该包含在类的声明?

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<? super T>>代替<T extends Comparable<T>>



文章来源: How to write a method signature “T that implements Comparable” in Java?