获取相似内容但未引用的哈希表密钥

时间:2018-07-18 01:27:46

标签: java hashtable

我有一些类似于以下的Java代码:它使用Hashtable来存储与三维点相对应的数据。

Hashtable<ThreeDimensionalPoint,data> table = new Hashtable<ThreeDimensionalPoint,data>();
table.put(new ThreeDimensionlPoint(1,1,1),new data());
table.get(new ThreeDimensionalPoint(1,1,1);

我想做的是仅从data对象的坐标中将ThreeDimensionalPoint从哈希表中取出。当然,第三行不起作用,因为.get通过引用而不是对象的内容来匹配键。

有人有解决方案吗?ThreeDimensionalPoint类具有三个指定坐标的整数。

3 个答案:

答案 0 :(得分:0)

您需要在类ThreeDimensionalPoint中重写equals和hashcode方法,例如以下示例(可以将其调整为您的确切代码):

class ThreeDimensionalPoint 
{

    public int cord1;
    public int cord2;
    public int cord3;

    ...

    @Override
    public boolean equals(Object obj)
    {
        // checking if both the object references are 
        // referring to the same object.
        if(this == obj)
            return true;

        // it checks if the argument is of the 
        // type ThreeDimensionalPoint by comparing the classes 
        // of the passed argument and this object.
        if(obj == null || obj.getClass()!= this.getClass())
            return false;

        // type casting of the argument. 
        ThreeDimensionalPoint threeDPoint = (ThreeDimensionalPoint) obj;

        // comparing the state of argument with 
        // the state of 'this' Object.
        return (threeDPoint.cord1 == this.cord1 && threeDPoint.cord2 == this.cord2 && threeDPoint.cord3 == this.cord3);
    }

    @Override
    public int hashCode()
    {
        int hash = 7;
        hash = 31 * hash + cord1;
        hash = 31 * hash + cord2;
        hash = 31 * hash + cord3;

        return hash;
    }

}

您可以在以下链接中找到有关此示例的更多信息: https://www.geeksforgeeks.org/equals-hashcode-methods-java/

答案 1 :(得分:0)

您需要重写equals类的hashCodeThreeDimensionalPoint方法。

假设ThreeDimensionalPoint的属性是尺寸(x,y,z),下面是从IntelliJ Idea生成的示例。

 @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Coordinate that = (Coordinate) o;

    if (x != that.x) return false;
    if (y != that.y) return false;
    return z == that.z;

}

@Override
public int hashCode() {
    int result = x;
    result = 31 * result + y;
    result = 31 * result + z;
    return result;
}
  

在覆盖equalshashCode时,应保持   请注意,

     

(1)如果您的equals方法返回两个对象相同,则   您的hashCode必须为他们两个返回相同的代码。除此以外,   您将在哈希表中看到不可预测的行为。

     

(2)尽管不是必需的,但是如果您的equals方法返回了这两个   那么对象不相等,hashCode应该尝试生成两个   这两个对象的值不同。这有助于取得更好的成绩   性能。

答案 2 :(得分:0)

不确定我是否正确理解了您的问题,而是因为仅跟踪3个坐标,而不是将对象用作键,为什么不将字符串作为键?

代替

Hashtable<ThreeDimensionalPoint,data> table = new Hashtable<ThreeDimensionalPoint,data>();
table.put(new ThreeDimensionlPoint(1,1,1),new data());
table.get(new ThreeDimensionalPoint(1,1,1));

为什么不

String tag = 1 + "-" + 1 + "-" + 1; // making it "1-1-1"
Hashtable<String,data> table = new Hashtable<String,data>();
table.put(tag,new data());
table.get("1-1-1");