Why can I not use .compareTo() when comparing the key of a a node in a BST to 0?

Bryan :
  • This is not all the code contained within the class, but if this is not enough I will add the rest as well.
  • add() is meant to add the value to the correct position in the BST using the key. If the key already exists, do nothing.
  • contains() is supposed to return True if the specified key is in the tree

    ```public class Node
    {
        public Node left;
        public Node right;
        public int key;
        public String value;
    
        public void add ( int key, String value )
        {
            if ( key.compareTo ( this.key ) < 0)
            {
                if ( left != null )
                    left.add ( key, value )
                else
                    left = new Node ( key, value );
            }
            else if ( key.compareTo ( this.key ) > 0 )
            {
                if ( right != null )
                    right.add ( key, value );
                else
                    right = new Node ( key, value);
            }
            else
                this.value = value;
        }
    
        public boolean contains ( int key )
        {
            if ( this.key == ( key ) )
                return value;
            if ( key.compareTo ( this.key ) < 0 )
                return left == null ? null : left.contains ( key );
            else
                return right == null ? null : right.contains ( key );
        }
    }
    
    
    
Jason :

The issue is that int is primitive and therefor does not implement Comparable so you cannot use int.compareTo, however the boxed variation Integer does. You can simply use Integer instead of int, or alternatively use Integer.compare(1, 2) and retain your usage of primitives.

public static class Node {
    public Node left;
    public Node right;
    public Integer key;
    public String value;

    public Node(Integer key, String value) {
        this.key = key;
        this.value = value;
    }

    public void add(Integer key, String value) {
        if (key.compareTo(this.key) < 0) {
            if (left != null)
                left.add(key, value);
            else
                left = new Node(key, value);
        } else if (key.compareTo(this.key) > 0) {
            if (right != null)
                right.add(key, value);
            else
                right = new Node(key, value);
        } else
            this.value = value;
    }

    public boolean contains(Integer key) {
        if (this.key.intValue() == (key)) {
            return true;
        }
        if (key.compareTo(this.key) < 0)
            return left == null ? null : left.contains(key);
        else
            return right == null ? null : right.contains(key);
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409722&siteId=1