Java 相等性检查
我有一个方法,可以检查BST的一个节点是否等于另一棵树的另一个节点(在输入中给出)——不管结构如何 这是我到目前为止所拥有的,但似乎我遗漏了一些东西Java 相等性检查,java,binary-search-tree,equals,Java,Binary Search Tree,Equals,我有一个方法,可以检查BST的一个节点是否等于另一棵树的另一个节点(在输入中给出)——不管结构如何 这是我到目前为止所拥有的,但似乎我遗漏了一些东西 public boolean sameValues(BSTInterface<T> other) { if(other == null && this != null) return false; else if(other.size() == 0 && this.siz
public boolean sameValues(BSTInterface<T> other)
{
if(other == null && this != null)
return false;
else if(other.size() == 0 && this.size() == 0)
return true;
Object temp = null;
Object temp2 = null;
while(other.preorderIterator().hasNext() && this.preorderIterator().hasNext())
{
temp = other.preorderIterator().next();
temp2 = this.preorderIterator().next();
if(temp.equals(temp2))
return true;
else
return false;
}
return false;
}
public boolean sameValues(其他接口)
{
如果(其他==null&&this!=null)
返回false;
else if(other.size()==0&&this.size()==0)
返回true;
对象温度=空;
对象temp2=null;
while(other.preordereditor().hasNext()&&this.preordereditor().hasNext())
{
temp=其他.preordereditor().next();
temp2=this.preordereditor().next();
如果(温度等于(温度2))
返回true;
其他的
返回false;
}
返回false;
}
有人知道更好的方法吗?
谢谢。由于多余的返回false,您的while()
循环在第一次迭代中终止。它应该看起来有点像:
while(other.preorderIterator().hasNext() && this.preorderIterator().hasNext())
{
temp = other.preorderIterator().next();
temp2 = this.preorderIterator().next();
if(temp.equals(temp2)) // same data found?
return true; // return success
// else // do not return! continue!
// return false;
}
return false;
}
由于多余的返回false,您的while()
循环在第一次迭代中终止。它应该看起来有点像:
while(other.preorderIterator().hasNext() && this.preorderIterator().hasNext())
{
temp = other.preorderIterator().next();
temp2 = this.preorderIterator().next();
if(temp.equals(temp2)) // same data found?
return true; // return success
// else // do not return! continue!
// return false;
}
return false;
}
首先,不需要检查this!=null,这是不可能发生的。现在,size()返回的是什么?节点是否包含某种数组?>如果是,则不应同时比较元素是否相等()如果大小!=0? 我假设preordereditor()。next()
返回节点的第一个子节点。为什么这与具有相同值的两个节点相关?难道你不能简单地比较两个节点的值吗?根据你的解释,我同意@ChrisTarazi-只比较节点的值。另外,您是否重写了equals()
?否则,使用Object.equals()
比较两个不同但等效的对象将不起作用。请查看while()
指令。它可以循环多少次…?对于这个,没有时间限制。首先,不需要检查这个!=null,这是不可能发生的。现在,size()返回的是什么?节点是否包含某种数组?>如果是,则不应同时比较元素是否相等()如果大小!=0? 我假设preordereditor()。next()
返回节点的第一个子节点。为什么这与具有相同值的两个节点相关?难道你不能简单地比较两个节点的值吗?根据你的解释,我同意@ChrisTarazi-只比较节点的值。另外,您是否重写了equals()
?否则,使用Object.equals()
比较两个不同但等效的对象将不起作用。请查看while()
指令。它能循环多少次…?没有时间限制。