java - 将我们自己的对象保存为 TreeMap 中的键

标签 java

我只是想知道在 TreeMap 中保存我们自己的对象时是否需要考虑任何因素。当我们将自己的对象保存为 HashMap 中的键时,类似的情况我们需要重写 equals 和 hashcode 方法以便以后能够检索它们。在树状图中没有哈希,使用黑红算法,但我不知道是否有什么特别的要做。 如果是这样,你能告诉我是否有什么需要考虑的吗?

谢谢

最佳答案

javadoc 说:

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time

因此,您需要正确实现自然排序,或者正确实现比较器。

它还说:

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

所以,如果你想遵守Map的一般契约(一般情况下你应该这样做),compareTo()方法必须与equals()一致,这意味着你需要正确实现一个equals()方法,以及传递性的 hashCode() 方法,并且您必须确保 a.equals(b) iff e.compareTo(b) == 0

大多数时候,人们会搞砸,因为他们实现了为两个对象返回 0 的compareTo/compare 方法,并且仍然期望映射认为这两个对象不同。

关于java - 将我们自己的对象保存为 TreeMap 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40960214/

相关文章:

java - 在android中添加edittext的值

java - 我怎样才能轻松地将 json 转换为自定义类型的 ArrayList?

java - 在单个 Spring 应用程序上下文中具有不同凭据的相同 Web 服务端口类型?

java - 100% CPU 在 javapns 中使用

将 1000000000000001 转换为基数 5 时出现 Java NumberFormatException

java - Java 中的 OpenCV EAST 文本检测器实现

java - Java中如何在同一目录下创建多个文件夹

Java UDP客户端未从服务器接收(简单客户端服务器udp代码)

java - 需要一个应用程序来修复带有未转义字符的 XML

java - 基于双端队列数组