实现 HashSet 的自定义对象

本文关键字:对象 自定义 HashSet 实现 | 更新日期: 2023-09-27 17:57:23

我正在使用HashSet进行算法处理,但是我在实现"自定义对象"时遇到了问题。做一些研究,似乎应该:

  • 覆盖等于和GetHashCode(上一个问题在这里)
  • 不应该生成带有可变对象的哈希码(这里是的,它是 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 中项目的count为 0。由于集合中没有项目,我怀疑我在实现中缺少一些东西,但无法找到有关准备自定义对象以在 HashSet 中使用的完整答案/教程。

实现 HashSet 的自定义对象

for(char c = 'A'; c < 'A'; c++)

调试器是你的朋友;检查你的循环条件。 那个循环体永远不会运行。 此外,GetHashCode的实现在添加对象后永远不会引起Count == 0,而不会引发异常。 最后,你对Equals的实现是错误的。

确保相同的对象引用不会被视为相等,如果您要实现引用相等,则无需首先覆盖它。