The Comparable
interface in Java allows objects of a class to be compared with each other to define a natural ordering. A class that implements Comparable
must override the compareTo()
method.
compareTo()
Method Signature:
public int compareTo(T o);
compareTo()
returns:
This mechanism is used by sorting algorithms to determine the order of elements.
compareTo()
returns positive (+ve
): the current object is considered greater and will be placed after the compared object in a sorted collection.compareTo()
returns negative (-ve
): the current object is considered smaller and will be placed before the compared object.compareTo()
returns 0
: both objects are considered equal.NOTE:
Obj1.compareTo(Obj2)
If Obj2 comes before the Obj1 then compareTo() return +ve else -ve.
import java.util.TreeSet;
class Employee implements Comparable<Employee> {
private String name;
private int id;
// Constructor
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
// Getters
public String getName() {
return name;
}
public int getId() {
return id;
}
// Overriding compareTo to compare by name
public int compareTo(Employee other) {
return this.name.compareTo(other.name);
}
// Overriding toString for better output representation
public String toString() {
return "Employee{name='" + name + "', id=" + id + "}";
}
}
public class TreeSetEmployeeExample {
public static void main(String[] args) {
// TreeSet will automatically sort Employee objects by name
TreeSet<Employee> employeeSet = new TreeSet<>();
// Adding employees
employeeSet.add(new Employee("John", 101));
employeeSet.add(new Employee("Alice", 102));
employeeSet.add(new Employee("Zara", 103));
employeeSet.add(new Employee("Bob", 104));
// Printing the sorted set
System.out.println("Employees sorted by name (TreeSet):");
for (Employee emp : employeeSet) {
System.out.println(emp);
}
}
}
Employees sorted by name (TreeSet):
Employee{name='Alice', id=102}
Employee{name='Bob', id=104}
Employee{name='John', id=101}
Employee{name='Zara', id=103}
Tree Explanation with Comparison Steps:
"John"
becomes the root of the tree."Alice".compareTo("John")
returns a negative value (-ve
), meaning "Alice"
is less than "John"
. So, "Alice"
goes to the left of "John"
."Zara".compareTo("John")
returns a positive value (+ve
), meaning "Zara"
is greater than "John"
. So, "Zara"
goes to the right of "John"
."Bob".compareTo("John")
returns a negative value (-ve
), meaning "Bob"
is less than "John"
."Bob".compareTo("Alice")
returns a positive value (+ve
), meaning "Bob"
is greater than "Alice"
. Therefore, "Bob"
goes to the right of "Alice"
.The insertion sequence builds the following tree:
John
/ \
Alice Zara
\
Bob
Inorder Traversal: [Alice, Bob, John< Zara]
xxxxxxxxxx
import java.util.*;
class Product implements Comparable<Product> {
private String name;
private double price;
// Constructor
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// Getters
public String getName() {
return name;
}
public double getPrice() {
return price;
}
// Overriding compareTo to compare by price
public int compareTo(Product other) {
// Using Double.compare for comparing prices (as price is a double)
return Double.compare(this.price, other.price);
}
// Overriding toString for better output representation
public String toString() {
return "Product{name='" + name + "', price=" + price + "}";
}
}
public class ProductSortingExample {
public static void main(String[] args) {
// Create a list of Product objects
List<Product> productList = new ArrayList<>();
productList.add(new Product("Laptop", 800.00));
productList.add(new Product("Smartphone", 500.00));
productList.add(new Product("Headphones", 50.00));
productList.add(new Product("Monitor", 300.00));
// Before sorting
System.out.println("Before Sorting by Price:");
for (Product p : productList) {
System.out.println(p);
}
// Sorting products by their price using Comparable (natural ordering)
Collections.sort(productList);
// After sorting
System.out.println("\nAfter Sorting by Price:");
for (Product p : productList) {
System.out.println(p);
}
}
}
Before Sorting by Price:
Product{name='Laptop', price=800.0}
Product{name='Smartphone', price=500.0}
Product{name='Headphones', price=50.0}
Product{name='Monitor', price=300.0}
After Sorting by Price:
Product{name='Headphones', price=50.0}
Product{name='Monitor', price=300.0}
Product{name='Smartphone', price=500.0}
Product{name='Laptop', price=800.0}
First Insertion: Laptop (Price 800.00)
"Laptop"
at 800.00
.Second Insertion: Smartphone (Price 500.00)
"Smartphone"
(500.00
) is less than "Laptop"
(800.00
).500.00.compareTo(800.00)
"Smartphone"
would go to the left of "Laptop"
, just like how a binary tree works.Third Insertion: Headphones (Price 50.00)
"Headphones"
(50.00
) is less than both "Laptop"
(800.00
) and "Smartphone"
(500.00
).50.00.compareTo(800.00)
50.00.compareTo(500.00)
"Headphones"
goes to the left of "Smartphone"
.Fourth Insertion: Monitor (Price 300.00)
"Monitor"
(300.00
) is less than "Laptop"
(800.00
), so compare it with "Smartphone"
(500.00
)."Monitor"
is less than "Smartphone"
but greater than "Headphones"
(50.00
).300.00.compareTo(800.00)
300.00.compareTo(500.00)
300.00.compareTo(50.00)
"Monitor"
goes to the right of "Headphones"
. (800.00)
/
(500.00)
/
(50.00)
\
(300.00)
Inorder Traversal: [50, 300, 500, 800]