How to write a method signature “T that implements Comparable<T>” in Java?

前提是你 提交于 2019-12-08 07:00:43

问题


What signature should I have on my insert-method? I'm struggling with the generics. In a way, I want both Comparable<T> and T and I have tried with <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:


Not sure what you are trying to achieve, but should you not include that in the declaration of the class?

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);
        }
    }
}

Note: it is good practice to use <T extends Comparable<? super T>> instead of <T extends Comparable<T>>



来源:https://stackoverflow.com/questions/11668850/how-to-write-a-method-signature-t-that-implements-comparablet-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!