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



我有一些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通过引用匹配键,而不是对象的内容。

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

您需要覆盖ThreeDimensionalPoint类的equalshashCode方法。

假设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必须为它们返回相同的代码。否则您将在Hashtable中看到不可预测的行为。

(2( 虽然不是必需的,但如果您的equals方法返回这两个如果对象不相等,则hashCode应尝试生成两个这两个对象的值不同。这有助于实现更好表演

您需要覆盖类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/

不确定我是否正确理解您的问题,但与其将对象用作键,既然您只跟踪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");

最新更新