Objects Implementing Comparable
If the objects are of the same type and implement the Comparable interface, they can be directly added to the Treeset. Here are some example programs.
An example of the above method is mentioned below:
Java
// Java Program to Get Two // Different Objects Into a TreeSet in Java // Using Comparable Interface import java.util.TreeSet; // Objects Implementing Comparable class Car implements Comparable<Car> { private String brand; private String model; public Car(String brand, String model) { this .brand = brand; this .model = model; } @Override public int compareTo(Car other) { int brandComparison = this .brand.compareTo(other.brand); return (brandComparison != 0 ) ? brandComparison : this .model.compareTo(other.model); } @Override public String toString() { return brand + " " + model; } } // Driver Class public class TreeSetExample { // main function public static void main(String[] args) { // TreeSet Initiated TreeSet<Car> carTreeSet = new TreeSet<>(); // Elements Added carTreeSet.add( new Car( "Toyota" , "Camry" )); carTreeSet.add( new Car( "Honda" , "Accord" )); carTreeSet.add( new Car( "Ford" , "Mustang" )); System.out.println( "Cars in TreeSet: " + carTreeSet); } } |
Cars in TreeSet: [Ford Mustang, Honda Accord, Toyota Camry]
Explanation of the above Method:
In this example, the Car class implements the Comparable interface to define the neutral ordering based on the car’s brand and model. The compareTo method is overriden to provide the comparison logic. The TreeSet then automatically maintains the elements in sorted order.
Get Two Different Objects Into a TreeSet in Java
In Java, TreeSet is a part of the Java Collection Framework and is located in the java.util package. It implements the NavigableSet interface and extends the AbstractSet and TreeSet is known for maintaining its elements in sorted order, either based on their natural order. This must be consistent with equals if it is to correctly implement the Set interface.
Methods of Getting Two Different Objects in a TreeSet in Java
In Java, if we want to store two different objects in TreeSet there are 2 ways.
- Comparable Interface
- CustomComparator