java - 为什么将 BST 中的 aa 节点的键与 0 进行比较时不能使用 .compareTo()?
问题描述
- 这不是类中包含的所有代码,但如果这还不够,我也会添加其余的。
- 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 ); } }
解决方案
问题是这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);
}
}
推荐阅读
- python - 查找闰年作业
- ios - xcode 9.4.1 控制台过滤器在断点命中时崩溃
- dns - 是否有关于谁拥有域名的永久记录/历史?
- excel-formula - Excel 公式 - SUMIF / INDEX / MATCH
- javascript - 如何使用 Ajax 将变量从 PHP 发送到 javascript?
- c# - 使用 C# 中的 COM 属性时出现错误 CS1545
- regex - 如何在 BASH 正则表达式中使用字符和锚点列表
- c# - OpenCV Marker Z 轴变换不正确
- c# - C# OutputDataReceived 到标签只显示最后一行
- c++ - 初始化一个 const char* 数组