这些是我的字段:
public class BSTSet <E> extends AbstractSet <E> {
// Data fields
private BSTNode root;
private int count = 0;
private Comparator<E> comp; // default comparator
/** Private class for the nodes.
* Has public fields so methods in BSTSet can access fields directly.
*/
private class BSTNode {
// Data fields
public E value;
public BSTNode left = null;
public BSTNode right = null;
// Constructor
public BSTNode(E v) {
value = v;
}
}
// Constructors - can either use a default comparator or provide one
public BSTSet() {
comp = new ComparableComparator(); // Declared below
}
public BSTSet(Comparator <E> c) {
comp = c;
}
// Methods
/** Return true iff the set is empty */
public boolean isEmpty() {
return count == 0;
}
/** Return the number of elements in set */
public int size() {
return count;
}
这是我想要解决的方法:
/** Return true iff (if and only if) the set contains an item
* (the item must be non null)
*/
public boolean contains(Object item) {
// YOUR CODE HERE
//changes item to E so it can be used in the comparator
E value1 = (E) item;
if (root.value.equals(item)){
return true;
}
int s = comp.compare(value1,root.value);
if(s<0){
if (root.left == null)
return false;
else
return root.left.contains(item);
}
else if(s>0){
if (root.right == null)
return false;
else
return root.right.contains(item);
}
}
到目前为止,一切似乎都没问题,但在返回root.left.contains(item)时失败了;并说它找不到符号 - 方法包含。我如何解决这个问题,以便我可以运行我的contains方法,该方法应返回该值是否在BST中?
答案 0 :(得分:2)
left
和right
都声明为BSTNode
个实例。 BSTNode
没有名为contains
的方法,因此您需要添加一个:
public boolean contains(Object item) {
return value.equals(item);
}
理想情况下,您希望节点和集合都实现相同的接口,因此您不知道实际调用的是哪个实现。