java - TreeMap 的先决条件

标签 java collections coding-style

就像要将对象插入到 HashMap 中一样,对象应该实现 equals() 和 hashcode() 方法(不一定)。 将对象插入 TreeMap 是否有任何特殊条件?

最佳答案

除非 ComparatorTreeMap 的构造函数中提供了相互比较键的方法,键必须实现 Comparable .

有关 TreeMap 构造函数的更多信息,请参阅 javadoc:http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html

编辑:作为@MeBigFatGuy指出强烈建议 key 覆盖 equals()同样,以实现与比较一致的方式。来自 TreeMap javadoc:

Note that the ordering maintained by a sorted map (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 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.

关于java - TreeMap 的先决条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463245/

相关文章:

java - 如何在不使用分割、子字符串或索引的情况下在某个字符处剪切字符串?

java - 如何根据 Java 中给定的一组比较器对作为字符串的 TreeMap 键进行排序

javascript - JavaScript应该放在哪里?

java - 有多种方法做同样的事情

java - 获取受影响的行数

hadoop - 结合使用JAVA API的kerberized webhdfs/hdfs

c# - ObservableCollection<T> 中的 block 重入

C++源码组织-COM口初始化

java - 如何增加下面代码中的ID值

objective-c - NSSet 的 containsObject 是否为 : test for pointer equality or value equality?