简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM