将对象添加到 HashSet

Adding Object to HashSet

我正在尝试将 Object (Exception) 添加到 Set,但是它添加了每个异常,尽管有些是重复的。 debug

在我的例子中,重复项是具有相同 Detail 消息的异常。

如果 Exception.getDetails() 不存在,我如何正确地将 Exceptions 添加到 HashSet

除了HashSet还有其他方法吗?

这里的性能是一个标准,二次解 (O(n^2)) 不是一个选项。

您需要重写 Execptions 的比较方式,以便它以您想要的方式识别重复项。您不能为 HashSet 执行此操作,但可以为 TreeSet 执行此操作,例如

Set<Exception> exceptions = new TreeSet<>(Comparator.comparing(Object::toString));

这个例子比较的是toString,在大多数情况下是异常类型和消息。

如果你真的想使用 HashSet,你需要将异常包装在 class 中,它实现了 hashCode 并等于你想要的方式。

如果您只关心类型和消息,您可以只存储每个异常的 toString

final Set<String> exceptions = new HashSet<>();

public void addException(Exception e) {
    exceptions.add(e.toString());
}

您需要重新定义 equalshashCode 方法。

如果 detailString 你可以重新定义它们如下

public boolean equals(Object obj) {
   if (!(obj instanceof YourException)) {
     return false;
   } 
   return getDetail().equals(((YourException) obj).getDetail());
}

public int hashCode() {
   return getDetail().hashCode();
}

将此代码视为编程的基础。例如,您必须检查空值。

一旦重新定义 equals 和 hashCode 在 TreeSet 中插入 YourException 是在 O(log(n)) 中完成的操作,其中 n 是大小集合的,来自 javadoc:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

您有几个选择:

  • 在您的异常 class
  • 中覆盖 hashcodeequals
  • 使用带有自定义 Comparator
  • TreeSet
  • 使用 Map<String, Exception>,其中键是 getDetails() 结果(例如 HashMap