开发者

Precondition for TreeMap

开发者 https://www.devze.com 2023-04-05 21:59 出处:网络
Like for a object to be inserted into a HashMap the object should implement the equals() and the hashcode() method(not necessarily).

Like for a object to be inserted into a HashMap the object should implement the equals() and the hashcode() method(not necessarily). Are there any special conditions for an obj开发者_Python百科ect to be inserted in a TreeMap ?


Unless a Comparator which mutually compares the keys is provided in the TreeMap's constructor, the keys must implement Comparable.

See the javadocs on TreeMap constructors for more information: http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html

EDIT: As @MeBigFatGuy points out it is highly recommended for keys to override equals() as well, in such a way that the implementation is consistent with the comparison. From the 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.


The type/class should (again, not necessarily) implement the Comparable interface (and override the compareTo method), so as to decide the ordering within the TreeMap.

0

精彩评论

暂无评论...
验证码 换一张
取 消