【发布时间】:2015-08-22 12:19:40
【问题描述】:
我有一个 ID 类。它指的是对一个独特的人的识别。身份证有两种形式。用户名和用户号。如果用户名匹配或用户编号匹配,则 ID 指的是同一个人。我想使用 ID 类作为哈希图中的键来查找人员。我重写了 equals 方法,以明确如果两个 ID 相等,则表示它们指的是同一个人。我假设我需要重写 hashCode() 方法,因为我想要 的哈希图。但我不知道怎么做。如何使 ID 类成为我的 HashMap 可接受的键?
public final class ID {
// These are all unique values. No 2 people can have the same username or id value.
final String username_;
final long idNumber_;
public ID(String username, Byte[] MACaddress, long idNumber) {
username_ = username;
idNumber_ = idNumber;
}
/**
* Checks to see if the values match.
* If either username or idNumber matches, then both ID's refer to the same person.
*/
public boolean equals(Object o) {
if (!(o instanceof ID)) {
return false;
}
ID other = (ID) o;
if (this.username_ != null && other.username_ != null) {
if (this.username_.equals(other.username_)) {
return true;
}
}
if (this.idNumber_ > 0 && other.idNumber_ > 0) {
if(this.idNumber_ == other.idNumber_) {
return true;
}
}
return false;
}
}
跟进:如果我想为唯一的社会安全号码添加第三个字段怎么办?这将如何改变我的人员查找哈希图和 ID 类?
请注意,hashCode 的维基百科页面显示:
The general contract for overridden implementations of this method is that they behave in a way consistent with the same object's equals() method: that a given object must consistently report the same hash value (unless it is changed so that the new version is no longer considered "equal" to the old), and that two objects which equals() says are equal must report the same hash value.
更新
迄今为止最好的解决方案: 为每个不可变的唯一标识符制作一个单独的 HashMap,然后将所有 HashMap 包装在一个包装器对象中。
【问题讨论】:
-
您是说,您将在地图中输入一个作为 ID 号的键,然后通过提供一个只是名称的 ID 来查找它?或者如果你输入一个数字 id,你将永远有一个数字 id,反之亦然?
-
@Jayan - 我怀疑这是重复的。 OP 没有询问合同细节/陷阱。就是如何根据他的要求设计它。
-
@prabugp >> 你是说,你会在地图中放一个作为 ID 号的键,然后通过提供一个只是名称的 ID 来查找它? -- 不。如果你查看了 equals 方法是如何实现的,要么 ID 必须匹配,要么名称必须匹配,或者两者都匹配,才能成为获取该 person 值的匹配键。这就像我创建了一个 ID,其中包含我的社会安全号码和我的姓名,然后我将它放在 HashMap 中,并带有一个引用我的值。然后有人创建了一个只是我的名字的新 ID,他们把它放在 hashmap 中,它返回给我。如果只是我的号码,也一样。
-
或者也许我改了名字但我的号码还是一样。然后有我的旧名字和号码的人仍然可以在哈希图中查找我,因为即使我的名字不匹配,我的号码也是匹配的。这有意义吗?