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. (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.
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.
精彩评论