为什么将BST中节点的键与0进行比较时不能使用.compareTo()?

问题描述 投票:1回答:1
  • 这不是该类中包含的所有代码,但是如果不够的话,我也会添加其余的代码。
  • add()意味着使用键将值添加到BST中的正确位置。如果密钥已经存在,则不执行任何操作。
  • contains()如果指定的键在树中,则应该返回True

    ```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 );
        }
    }
    
    
    
java binary-search-tree compareto
1个回答
0
投票

问题在于,int是原始的,因此没有实现Comparable,因此您不能使用int.compareTo,而装箱的Integer则可以。您可以简单地使用Integer而不是int,或者使用Integer.compare(1,2)并保留对原语的使用。

    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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.