Search code examples
javagenericscomparable

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


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

Solution

  • 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>>