1

i want to create a generic bst , every node has key and value,the methods and will work by the key. do i have to extends comparable in the Tree class? or only in the node class?

i tried to figure out if i have to extends comparable by the node,or only by the key its enough.


public class ThreadedGenericNode<K,V> implements Comparable<ThreadedGenericNode<K,V>>
{
    K _key;
    V _value;
    private ThreadedGenericNode _right;
    private ThreadedGenericNode _left;
    private ThreadedGenericNode _parent;
    private boolean isThreadedRight;
    private boolean isThreadedLeft;


    public ThreadedGenericNode(K key,V value)
    {
        this._right = null;
        this._left = null;
        this._parent = null;
        this.isThreadedLeft = true;
        this.isThreadedRight = true;
        this._key = key;
        this._value = value;
    }




       @Override
    public int compareTo(ThreadedGenericNode<K, V> o) {

        if(this._key > o._key)
            return 1;

        return 0;
    }


}

i got compile error : "The operator > is undefined for the argument type(s) K"

so i have to use K extends Comparable? or implements? finally the key will be integer, so what is the way to do that?

Agar123
  • 95
  • 7

1 Answers1

1

You cannot use < operator with generics. If you passed for example String type as K what should happens using > operator ? Moreover in runtime generic types are erased to Object.

Your best choice is to make sure K will will implement Comparable interface and use compareTo on your K type. So you should use bounded type on your K :

public class ThreadedGenericNode<K extends Comparable<K>, V> implements Comparable<ThreadedGenericNode<K, V>> {
    K _key;

    .......

    @Override
    public int compareTo(ThreadedGenericNode<K, V> o) {

        return this._key.compareTo(o._key);
    }
}

If you say that in the end K will be an Integer only - what is the point of using generics then? By using generics you want to have flexibility of using your class with different types and still have compile time checking of those types.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
  • thanks! do i have to change to : public class ThreadedGenericNode, V> implements Comparable, V>> or what you write is enough? – Agar123 Jul 07 '19 at 14:16
  • Try to compile what you have just written :) you will get an error with unexpected bound in second comparable. – Michał Krzywański Jul 07 '19 at 14:21
  • thank you!! and you right about the question,it was homework and i did with int, and now we study generic so i want to do that generic. thank you very much!!! – Agar123 Jul 07 '19 at 14:33