Jane Foster
Jane Foster

Reputation: 471

How to implement a compareTo( ) method for generic objects?

I am stuck on defining the compareTo method for a generic class.

I have created a generic class BinarySearchTree:

public class BinarySearchTree<K extends Comparable<K>, V>{
    Node root;

    private class Node{
        K key;
        V value;
        Node left=null;
        Node right=null;

        public Node(K k, V v){ key=k; value=v; }
    }
    ...

   private int compareTo(K k){

   }
}

The compareTo method is to compare two instances of generic type K. If they are equal, return zero. If this is smaller than k, return -1, otherwise return 1.

I use equals() to check if they are equal. However, I am stuck on the remaining comparisons.

Upvotes: 0

Views: 736

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

you should not compare a Node<K> with a K. If you need to do comparisons from the outside, why not just expose the K with a getter?

Upvotes: 1

Related Questions