RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Oct 9, 2009

Using Tree(Map,Set) in Collections

Here's the problem: You can't put objects that don't implement the Comparable interface inside a Tree(Map/Set); if you do, your code won't even compile. The underlying cause is simple; TreeMap attempts to sort the objects you add. Many common types, such as String, Integer, etc., already implement Comparable, so they will be sorted automatically and cause no problems.

The workaround is simple as well. To add your own objects, simply override the compareTo method of the Comparable interface and specify the order in which you want them to sort.

Sivaranjani Duraisamy
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date