2

I have this simple node:

public class Node<T> implements Comparable<Node>{
    T value; 
    Node<T> next; 
    public Node(T value){
        this.value = value; 
        this.next = null; 
    }
    public int compareTo(Node other){
        return this.value.compareTo(other.value); 
    }
}

Eclipse is asking me to cast "this.value". Casting it with int doesnt work. How should it be done?

  • you are defining `compareTo` for type `T`, inside of which you are invoking `compareTo` on `this.value` which is again type `T`. See it as this way : before you define `compareTo` on a type, how can you call `compareTo` on that type ? – SomeDude Jul 30 '16 at 02:18
  • Nope, I've just tried it and not working either. –  Jul 30 '16 at 02:20
  • but thank you for trying to help. –  Jul 30 '16 at 02:20

1 Answers1

4

Your declaration of T does not "extend" Comparable, so you can't use it to compare.

You could change it to:

public class Node<T extends Comparable<T>> implements Comparable<Node<T>>{
    T value; 
    Node<T> next; 
    public Node(T value){
        this.value = value; 
        this.next = null; 
    }
    public int compareTo(Node<T> other){
        return this.value.compareTo(other.value); 
    }
}

This assumes that T implements Comparable. Otherwise, if T is not really a comparable, you may just do the comparison at the Node level. But you should probably still declare your class like this

public class Node<T extends Something>

so that you have methods from Something to work with when doing the comparison.

If I go back at the beginning: When you instantiate your Node, you do something like this:

Node<MyType> node = new Node<MyType>();

MyType becomes your T. Is MyType a comparable ? If so, you may declare your class as shown above. Otherwise, you will not be able to do T.compareTo (aka MyType.compareTo), so you need to perform your comparison using other fields from MyType.

I hope this is clear enough..

alexbt
  • 16,415
  • 6
  • 78
  • 87