java:对象1和对象2与对象2和对象1相同

标签 java unique hashcode

我尝试在不同的 GridPositions(x,y) 之间绘制线条。每个 GridPos 有 4 个连接北、东、南、西。问题是,如果我从 GridPos(1,1) 到 GridPos(2,2) 画一条线,程序稍后还会在 GridPos(2,2) 和 GridPos(1,1) 之间画一条相反方向的线。

我尝试用这个类解决问题(WarpGate 与 GridPos 相同):

public class GateConnection {

private WarpGate gate1 = null;
private WarpGate gate2 = null;

public GateConnection(WarpGate gate1, WarpGate gate2) {
    super();
    this.gate1 = gate1;
    this.gate2 = gate2;
}

@Override
public int hashCode() {
    final int prime = 31;

    int result = prime * ((gate1 == null) ? 0 : gate1.hashCode());
    result += prime * ((gate2 == null) ? 0 : gate2.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    GateConnection other = (GateConnection) obj;
    if ((gate1.equals(other.gate1) || gate1.equals(other.gate2)) && (gate2.equals(other.gate2) || gate2.equals(other.gate1))) {
        return true;
    }
    return false;
}

}

这个类可以添加到 HashSet 中,双重绘制就会消失,但我不知道 hashValue 是否始终是唯一的。

WarpGate 的哈希码(由 eclipse 自动生成):

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + gridX;
    result = prime * result + gridY;
    return result;
}

现在我使用ArrayList。我查看 GateConnection 是否存在,如果不存在则添加。但这个版本比使用 HashSet 需要更多的资源。

编辑:

白色矩形是绘制的连接,数字是 GridPositions(x|y),红色箭头是绘制矩形的两个方向,因为 GridPos(2|2) 与 GridPos(4|) 有连接。 2) 和 (4|2) 至 (2|2) enter image description here

最佳答案

TreeSet既不使用hashCode()也不使用equals()。它使用 compareTo(),但您应该确保它与 equals() 一致,以尊重 Set 语义。

对于HashSet,存储对象的hashCode()不必必须是唯一的。事实上,如果您愿意,您可以为每个项目返回相同的代码,并且如果您的 equals() 正确实现,它们仍然会被存储而不会丢失任何项目。好的 hashCode() 只会提高性能。

唯一的关键规则是两个相等的项必须生成相同的哈希代码。

只要您能保证同一 GateConnection 对象中的 gate1gate2 永远不相等,您的实现看起来就不错。如果它们相等,则两个 GateConnection 对象可能具有不同的哈希码,但会报告为相等。如果它们存储在 HashSet 中,这将导致不可预测的行为。

例如GateConnection((1,1), (1,1)) 等于 GateConnection((1,1), (7,9)),但哈希码不同。

关于java:对象1和对象2与对象2和对象1相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596171/

相关文章:

c# - 在 C# 中高效查找二维数组 T[][] 中的唯一元素

.net - 如何在 .net 中获取数组的唯一值?

java - 按下按钮时 JTextField 自动更改值

java - 如何以主从模式将任务从主服务器传递给从服务器

c# - 生成代码系列并考虑以前的代码

java - equals 和 hashcode 的不同字段

wpf 重写 ContentControl 中的 getHashCode 和 Eqaul

java - 为什么RC4无法处理大量加密数据?

java - 使用 URL 上的 Scanner 类引发病毒?

java - 如何确保 hashCode() 与 equals() 一致?