【发布时间】:2015-09-07 10:47:22
【问题描述】:
我将 HashSet 用于算法目的,但我在“自定义对象”的实现方面遇到了问题。做一些研究似乎应该:
- 覆盖 Equals 和 GetHashCode (previous question here)
- 不应使用可变对象生成哈希码(here 是的,它是 Java,但我认为实现已经足够接近)
我的实现:
//Simplified version of actual class with key components
class customObject {
public readonly uint column;
public readonly char row;
public customObject(uint column, char row) {
this.column = column;
this.row = row;
}
public override bool Equals(object obj) {
return obj is customObj && !ReferenceEquals(this, obj);
}
/*where uint column and char row are readonly. HashSet add is not called
until these variables are set with their lifetime value.*/
public override int GetHashCode() {
unchecked {
var hashCode = row.GetHashCode();
hashCode = (hashCode * 397) ^ column.GetHashCode();
return hashCode;
}
}
}
//somwhere else
HashSet<customObject> s = new HashSet<customObject>();
for(int i = 0; i < 10; i++) {
for(char c = 'A'; c < 'J'; c++) {
s.add(new customObject((uint)i,c));
}
}
很遗憾,我无法将自定义对象添加到 HashSet。在尝试添加对象后,我可以确认 HashSet 中项目的 count 为 0。由于集合中没有项目,我怀疑我在实现中遗漏了一些东西,但一直无法找到有关准备自定义对象以在 HashSets 中使用的完整答案/教程。
【问题讨论】:
-
首先你的
Equals是错误的。其次,当您不发布此代码时,很难看到您的 Hashset 的问题(顺便说一句:在这里也添加对象的定义......例如:what 是 @ 987654326@?) -
代码看起来不错(除了我不确定为什么您的
ReferenceEquals被否定)。您如何将对象添加到您的HashSet?你有什么例外吗? -
@vesan 我正在添加 set.add(obj)
-
请发布真实 工作代码...
-
1.您的代码仍然无法编译。 2. 如果我修复了所有语法错误,它会按预期工作。发布您正在运行的出现问题的实际代码。