我正在使用 BinaryNode 实现一个二叉搜索树来存储数据。我在我的 add 中使用了 CompareTo 方法,并包含确定该项目所属的子树的方法。我在使用 compare 的各个地方不断收到此错误:
BST.java:50: error: cannot find symbol
if (item.CompareTo(root.data) > 0)
^
symbol: method CompareTo(T)
location: variable item of type T
where T is a type-variable:
T extends Comparable<? super T> declared in class BST
这是我的代码,我做错了什么?
import java.util.List;
import java.util.ArrayList;
import java.util.*;
import java.io.*;
public class BST<T extends Comparable<? super T>> implements BSTInterface<T>
{
private BinaryNode<T> root;
private int numberOfItems;
public List<T> preOrder = new ArrayList<T>();
public List<T> inOrder = new ArrayList<T>();
public List<T> postOrder = new ArrayList<T>();
public BST()
{
root = null;
numberOfItems = 0;
}
public BST(T rootData)
{
root = new BinaryNode<T>(rootData);
numberOfItems = 1;
}
public BST(T rootData, BST<T> leftTree, BST<T> rightTree)
{
root = new BinaryNode<T>(rootData);
numberOfItems = 1;
root.left = leftTree.root;
root.right = rightTree.root;
}
public void setTree(T rootData)
{
root = new BinaryNode<T>(rootData);
}
public boolean contains(T item)
{
if (root.data.equals(item))
return true;
else
{
if (item.CompareTo(root.data) > 0)
{
root = root.left;
return contains(item);
}
else if (item.CompareTo(root.data) < 0)
{
root = root.right;
return contains(item);
}
else
return false;
}
}
public void add(T newItem)
{
if (root == null)
{
root = new BinaryNode<T>(newItem);
numberOfItems++;
}
if (newItem.equals(root.data))
return;
if (newItem.CompareTo(root.data) < 0)
{
root = root.left;
add(newItem);
}
if (newItem.CompareTo(root.data) > 0)
{
root = root.right;
add(newItem);
}
}