【问题标题】:HashSet Contains function not working properlyHashSet 包含函数无法正常工作
【发布时间】:2019-03-28 20:12:16
【问题描述】:
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 的实现,我认为它们很好,因为它们比较了 State 的所有属性。

任何提示将不胜感激。

【问题讨论】:

  • 错字:大概if(anotherState instanceof MazeState)return false; 应该检查它是否不是实例
  • 另外,cheeses 是什么?如果这个集合包含你定义的对象,你还需要为cheese's实现equals(Object o)

标签: java contains hashset


【解决方案1】:

我认为您想在此处应用 NOT 检查....所以,以下将起作用

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

更新

此外,即使 cheeses 集合的元素顺序不同, containsAll 检查也会报告两个对象相等。

【讨论】:

  • 喜欢有人在 cmets 上发布已经给出的答案。
  • @Pants 嗯...当不同的人在阅读问题的同时发布答案和添加 cmets 时会发生重复...这并不是故意的。
  • 没错,但它仍然会检查已经探索过的节点。
  • 您能否分享更多详细信息,如究竟发生了什么?
  • 您正在执行 containsAll 检查,这意味着具有相同元素但顺序不同的两个集合将导致它们被报告为相等
猜你喜欢
  • 2016-10-03
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 2017-12-15
  • 2013-03-27
  • 2012-08-15
  • 2013-11-05
相关资源
最近更新 更多