小编por*_*che的帖子

HashSet.contains 不应该返回 false

我有这个代码:

public class Tray {

private Set<Block> blocks;

private int numColumns;
private int numRows;

//constructor
public Tray (int numRows, int numColumns){
    this.numColumns = numColumns;
    this.numRows = numRows;
    blocks = new HashSet<>();
}

public boolean satisfiesGoal(Tray other){

    Block thisBlock = this.blocks.iterator().next();
    Block otherBlock = other.blocks.iterator().next();

    boolean hashesEqual = thisBlock.hashCode() == otherBlock.hashCode(); // this is true

    boolean areEqual = thisBlock.equals(otherBlock) && otherBlock.equals(thisBlock); // this is true

    boolean contains = this.blocks.contains(otherBlock); // this is false, why?
    return contains;
}
Run Code Online (Sandbox Code Playgroud)

在主要方法中,我已将 2 个块添加到各自的托盘中。根据调试器,变量“hashesEqual”和“areEqual”为真,但布尔值“contains”为假。关于为什么根据“equals”方法,2 个对象的哈希值会相等,但不会在 …

java hash equals hashcode hashset

5
推荐指数
1
解决办法
4553
查看次数

标签 统计

equals ×1

hash ×1

hashcode ×1

hashset ×1

java ×1