哈希集包含函数无法正常工作


while(!open.isEmpty()&& !solutionFound){
Node selected=open.poll();//fifo
State estado=selected.getState();
estado.toString();
this.exploredNodes++;       
if(!explored.contains(selected.getState())  ){
if(problem.testGoal(selected.getState())){
actionSequence=recoverPath(selected, inicial);//return array with solutions
solutionFound=true;
}
//totalCost++;
successors=getSuccessors(selected);
for(Node successor : successors){
//if(!explored.contains(successor))
open.add(successor);
}
explored.add(selected.getState());
}
}

我正在尝试检查所选节点的状态是否在节点的哈希集中,如果它已经在其中,那么它不应该做任何事情。

问题是它总是返回 false。因此可以无限比较。

@Override
public boolean equals(Object anotherState) {
if(anotherState instanceof MazeState)return false;

if(this.life!=((MazeState)anotherState).life)return false;
if (this.position.x!=((MazeState)anotherState).position.x)return false;
if (this.position.y!=((MazeState)anotherState).position.y)return false;
if (!this.cheeses.containsAll(((MazeState)anotherState).cheeses))return false;
return true;

}
@Override
public int hashCode() {
return Objects.hash(this.position,this.life,this.cheeses);

这是我对 equals 和 hashCode 的实现,我认为这很好,因为它们比较了状态的所有属性。

任何提示将不胜感激。

我想你想在这里应用一个 NOT 检查....因此,以下内容将起作用

if(!(anotherState instanceof MazeState)) return false;

更新

此外,containsAll 检查将报告两个对象相等,即使奶酪集合具有不同顺序的元素。

最新更新