devxlogo

Using Tree(Map,Set) in Collections

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist