我有这个代码:
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 个对象的哈希值会相等,但不会在 …