就像要将对象插入到 HashMap 中一样,对象应该实现 equals() 和 hashcode() 方法(不一定)。 将对象插入 TreeMap 是否有任何特殊条件?
最佳答案
除非 Comparator在 TreeMap
的构造函数中提供了相互比较键的方法,键必须实现 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. (SeeComparable
orComparator
for a precise definition of consistent with equals.) This is so because theMap
interface is defined in terms of the equals operation, but a map performs all key comparisons using itscompareTo
(orcompare
) 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 theMap
interface.
关于java - TreeMap 的先决条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463245/