Java TreeSet/Contains方法
作为练习,我尝试实现自己的Java TreeSet/Contains方法,java,collections,treeset,Java,Collections,Treeset,作为练习,我尝试实现自己的TreeSet。在编写add和remove方法之前,我更喜欢从contains开始,它看起来更简单,但我被卡住了 我的树由节点和叶组成: static class Leaf<E extends Comparable<E>> implements Tree<E> { //stuff @Override public boolean contains() {
TreeSet
。在编写add和remove方法之前,我更喜欢从contains开始,它看起来更简单,但我被卡住了
我的树由节点
和叶
组成:
static class Leaf<E extends Comparable<E>> implements Tree<E> {
//stuff
@Override
public boolean contains() {
return false;
}
}
我怎么能对我的树说,用元素查看它的好部分(左或右)?使用递归
正如您可以看到的那样,叶
对象构成了树
的结尾,因此它将是方法的停止条件
您可以看到,将存储在树中的对象必须实现可比较的。因此,包含可以如下所示:
@Override
public boolean contains(E elem) {
int compare = elem.compareTo(value); //here we compare the element with
//the compareTo method that the objects
//used must redefined
if(compare==0)
return true; //here the current node contains elem !
else if(compare < 0)
return left.contains(elem); //elem is inferior than the elem present in the current node hence we look into the left part of the tree
else
return right.contains(elem); //elem is superior than the elem present in the current node hence we look into the right part of the tree
}
@覆盖
公共布尔包含(E元素){
int compare=elem.compareTo(value);//这里我们将元素与
//对象所使用的compareTo方法
//必须重新定义所使用的
如果(比较==0)
return true;//此处当前节点包含元素!
否则如果(比较<0)
return left.contains(elem);//elem不如当前节点中的elem,因此我们查看树的左侧部分
其他的
return right.contains(elem);//elem优于当前节点中存在的elem,因此我们查看树的右侧部分
}
正如您所看到的,如果元素不在树中
,那么我们将在末尾的叶中
,它将返回false
您可以对代码添加和删除使用递归实现相同的逻辑
正如您可以看到的那样,叶
对象构成了树
的结尾,因此它将是方法的停止条件
您可以看到,将存储在树中的对象必须实现可比较的。因此,包含可以如下所示:
@Override
public boolean contains(E elem) {
int compare = elem.compareTo(value); //here we compare the element with
//the compareTo method that the objects
//used must redefined
if(compare==0)
return true; //here the current node contains elem !
else if(compare < 0)
return left.contains(elem); //elem is inferior than the elem present in the current node hence we look into the left part of the tree
else
return right.contains(elem); //elem is superior than the elem present in the current node hence we look into the right part of the tree
}
@覆盖
公共布尔包含(E元素){
int compare=elem.compareTo(value);//这里我们将元素与
//对象所使用的compareTo方法
//必须重新定义所使用的
如果(比较==0)
return true;//此处当前节点包含元素!
否则如果(比较<0)
return left.contains(elem);//elem不如当前节点中的elem,因此我们查看树的左侧部分
其他的
return right.contains(elem);//elem优于当前节点中存在的elem,因此我们查看树的右侧部分
}
正如您所看到的,如果元素不在树中
,那么我们将在末尾的叶中
,它将返回false
您可以对代码添加
和删除
实现相同的逻辑
我如何对我的树说,用元素查看它的好部分(左或右)
那么,您需要使用compareTo
将elem
与value
进行比较。如果结果为0,则值已经相等,您可以返回true
如果elem
小于value
,则可以递归到left.contains(elem)
,否则递归到right.contains(elem)
。如果left
或right
值只是一个叶,那么它将返回false
,否则它将相应地向下递归
我如何对我的树说,用元素查看它的好部分(左或右)
那么,您需要使用compareTo
将elem
与value
进行比较。如果结果为0,则值已经相等,您可以返回true
如果elem
小于value
,则可以递归到left.contains(elem)
,否则递归到right.contains(elem)
。如果left
或right
值只是一个叶,那么它将返回false
,否则它将相应地向下递归