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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: