【问题标题】:Implementing custom object for HashSet为 HashSet 实现自定义对象
【发布时间】: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. 如果我修复了所有语法错误,它会按预期工作。发布您正在运行的出现问题的实际代码。

标签: c# hash hashcode hashset


【解决方案1】:
for(char c = 'A'; c < 'A'; c++)

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

它确保相同的对象引用将被视为相等,并且如果您要进行引用相等,那么您不需要首先覆盖它。

【讨论】:

  • c
  • 所以您真正的问题是仍然您不想显示实际代码?
猜你喜欢
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多