Does Sort Work With Comparable? Understanding Java Sorting

Does Sort Work With Comparable in Java? Yes, the sort() method in Java collections framework leverages the Comparable interface for sorting objects. On compare.edu.vn, we demystify this process, explaining how Comparable defines the natural ordering of objects, enabling seamless sorting using Collections.sort() or Arrays.sort(). This guide covers implementation details, benefits, and potential pitfalls of using Comparable for efficient data organization. You’ll find the most comprehensive comparison and data organization here.

1. What Is the Comparable Interface in Java?

The Comparable interface in Java is a fundamental part of the java.lang package, and it’s crucial for sorting objects. This interface provides a way to define a natural ordering for a class, allowing its instances to be compared with each other. Let’s dive into what makes the Comparable interface so important and how it functions.

1.1. Defining Natural Ordering

The primary purpose of the Comparable interface is to define a natural ordering for objects of a class. Natural ordering implies a default way of comparing objects, which is inherently meaningful for that class. For example, the natural ordering for String objects is lexicographical (alphabetical) order, and for Integer objects, it’s numerical order.

1.2. The compareTo() Method

The Comparable interface contains a single method, compareTo(), which must be implemented by any class that implements Comparable. The method signature is:

int compareTo(T o)

Here, T is the type of the object being compared. The compareTo() method compares the current object with another object of the same type and returns an integer value indicating their relative order.

1.3. Return Values of compareTo()

The compareTo() method returns one of the following values:

  • Negative Integer: If the current object is less than the specified object.
  • Zero: If the current object is equal to the specified object.
  • Positive Integer: If the current object is greater than the specified object.

For example, if you are comparing two Integer objects, a and b, a.compareTo(b) will return:

  • A negative value if a is less than b.
  • Zero if a is equal to b.
  • A positive value if a is greater than b.

1.4. Implementing Comparable

To implement the Comparable interface, a class must:

  1. Declare that it implements the Comparable interface.
  2. Provide an implementation for the compareTo() method.

Here’s an example of a Person class implementing Comparable based on age:

class Person implements Comparable<person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age);
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}
</person>

In this example, the compareTo() method compares the ages of two Person objects.

1.5. Benefits of Using Comparable

  • Simplicity: It provides a straightforward way to define how objects of a class should be compared.
  • Integration with Java Collections: Many Java collection classes, such as TreeSet and TreeMap, use the Comparable interface to maintain elements in a sorted order.
  • Default Sorting: Methods like Collections.sort() and Arrays.sort() can automatically sort lists and arrays of objects that implement Comparable.

1.6. Example: Sorting a List of Person Objects

Using the Person class defined above, you can easily sort a list of Person objects:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableExample {
    public static void main(String[] args) {
        List<person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        System.out.println("Before sorting: " + people);
        Collections.sort(people);
        System.out.println("After sorting: " + people);
    }
}
</person>

Output:

Before sorting: [Alice (30), Bob (25), Charlie (35)]
After sorting: [Bob (25), Alice (30), Charlie (35)]

1.7. Common Pitfalls

  • Inconsistent equals() and compareTo(): It’s crucial to ensure that your compareTo() method is consistent with your equals() method. If two objects are equal according to equals(), their compareTo() method should return 0.
  • Null Handling: Be careful when handling null values in your compareTo() method. A common approach is to throw a NullPointerException or handle nulls in a way that makes sense for your application.
  • Type Safety: Ensure that you are only comparing objects of the same type within the compareTo() method to avoid ClassCastExceptions.

1.8. Relationship with Comparator

While Comparable defines the natural ordering of a class, the Comparator interface provides a way to define alternative orderings. A Comparator is an external class that can compare objects of another class. This is particularly useful when you need to sort objects in multiple different ways or when you don’t have control over the class itself.

For instance, you might want to sort Person objects by name instead of age. You can define a Comparator for this purpose:

import java.util.Comparator;

class PersonNameComparator implements Comparator<person> {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
}
</person>

You can then use this Comparator with Collections.sort():

people.sort(new PersonNameComparator());
System.out.println("Sorted by name: " + people);

Output:

Sorted by name: [Alice (30), Bob (25), Charlie (35)]

1.9. Core Java Classes Implementing Comparable

Many core Java classes implement the Comparable interface, including:

  • String: Implements lexicographical ordering.
  • Integer, Double, Float, Long: Implement numerical ordering.
  • Date, Calendar: Implement chronological ordering.

This means you can directly sort collections of these objects without needing to implement Comparable yourself.

1.10. Conclusion

The Comparable interface is a powerful tool in Java for defining the natural ordering of objects. By implementing the compareTo() method, classes can specify how their instances should be compared, enabling easy sorting and integration with Java’s collection framework. Understanding and correctly implementing Comparable is essential for writing efficient and maintainable Java code.

2. How Java’s compareTo() Method Works

The compareTo() method is the heart of the Comparable interface in Java. It’s used to compare the current object with another object of the same type and determine their relative order. Understanding how this method works is crucial for implementing the Comparable interface correctly and ensuring that your objects are sorted as expected.

2.1. Basic Structure of compareTo()

The compareTo() method has the following signature:

int compareTo(T o)

Where T is the type of the object being compared. This method compares the current object (i.e., this) with the object o and returns an integer value that indicates their relative order.

2.2. Return Values: Significance

The integer value returned by compareTo() indicates the relationship between the two objects:

  • Negative Integer: The current object is less than the specified object (this < o).
  • Zero: The current object is equal to the specified object (this == o).
  • Positive Integer: The current object is greater than the specified object (this > o).

2.3. Implementing compareTo(): Step-by-Step

To implement the compareTo() method effectively, follow these steps:

  1. Type Check: Ensure that the object being compared is of the correct type.
  2. Comparison Logic: Implement the logic to compare the relevant attributes of the objects.
  3. Return Value: Return a negative, zero, or positive integer based on the comparison result.

2.4. Example: Comparing Integer Objects

Let’s start with a simple example using Integer objects:

Integer a = 5;
Integer b = 10;

int result = a.compareTo(b);

if (result < 0) {
    System.out.println("a is less than b");
} else if (result == 0) {
    System.out.println("a is equal to b");
} else {
    System.out.println("a is greater than b");
}

In this case, a.compareTo(b) returns a negative integer because 5 is less than 10.

2.5. Example: Implementing compareTo() in a Custom Class

Let’s implement the compareTo() method in a custom class, Book, to compare books based on their number of pages:

class Book implements Comparable<book> {
    private String title;
    private int pages;

    public Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    public String getTitle() {
        return title;
    }

    public int getPages() {
        return pages;
    }

    @Override
    public int compareTo(Book other) {
        return Integer.compare(this.pages, other.pages);
    }

    @Override
    public String toString() {
        return title + " (" + pages + " pages)";
    }
}
</book>

In this example, Integer.compare(this.pages, other.pages) is used to compare the number of pages. This is a convenient utility method in the Integer class that simplifies the comparison.

2.6. Using compareTo() to Sort a List of Book Objects

Now, let’s use the Book class to sort a list of books:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CompareToExample {
    public static void main(String[] args) {
        List<book> books = new ArrayList<>();
        books.add(new Book("The Lord of the Rings", 1178));
        books.add(new Book("Pride and Prejudice", 432));
        books.add(new Book("1984", 328));

        System.out.println("Before sorting: " + books);
        Collections.sort(books);
        System.out.println("After sorting: " + books);
    }
}
</book>

Output:

Before sorting: [The Lord of the Rings (1178 pages), Pride and Prejudice (432 pages), 1984 (328 pages)]
After sorting: [1984 (328 pages), Pride and Prejudice (432 pages), The Lord of the Rings (1178 pages)]

The Collections.sort() method uses the compareTo() method defined in the Book class to sort the books based on the number of pages.

2.7. Chaining Comparisons

In some cases, you might want to compare objects based on multiple criteria. For example, you might want to sort books first by the number of pages and then by title. You can achieve this by chaining comparisons in the compareTo() method:

class Book implements Comparable<book> {
    private String title;
    private int pages;

    public Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    public String getTitle() {
        return title;
    }

    public int getPages() {
        return pages;
    }

    @Override
    public int compareTo(Book other) {
        int pageComparison = Integer.compare(this.pages, other.pages);
        if (pageComparison != 0) {
            return pageComparison;
        }
        return this.title.compareTo(other.title);
    }

    @Override
    public String toString() {
        return title + " (" + pages + " pages)";
    }
}
</book>

In this modified compareTo() method, the books are first compared based on the number of pages. If the number of pages is the same, then the books are compared based on their titles.

2.8. Important Considerations

  • Consistency with equals(): The compareTo() method should be consistent with the equals() method. If a.equals(b) is true, then a.compareTo(b) should return 0.
  • Transitivity: The compareTo() method should be transitive. If a.compareTo(b) > 0 and b.compareTo(c) > 0, then a.compareTo(c) should also be greater than 0.
  • Symmetry: While compareTo() doesn’t need to be symmetric (i.e., a.compareTo(b) doesn’t need to be the negation of b.compareTo(a)), it should provide a consistent ordering.

2.9. Using Utility Methods for Comparison

Java provides several utility methods to simplify the comparison process:

  • Integer.compare(int x, int y): Compares two integers.
  • Double.compare(double x, double y): Compares two doubles.
  • String.compareTo(String anotherString): Compares two strings lexicographically.

Using these utility methods can make your compareTo() implementation cleaner and more readable.

2.10. Conclusion

The compareTo() method is a powerful tool for defining the natural ordering of objects in Java. By correctly implementing this method, you can ensure that your objects are sorted as expected and that your classes integrate seamlessly with Java’s collection framework. Understanding the nuances of compareTo() and following best practices will lead to more robust and maintainable code.

3. Sorting a Java Array Using Comparable

In Java, sorting an array of objects that implement the Comparable interface is a straightforward process. The Arrays.sort() method is used to sort the elements of an array in ascending order, according to the natural ordering defined by the compareTo() method. Let’s explore how to sort Java arrays using Comparable with detailed examples and explanations.

3.1. Basic Usage of Arrays.sort()

The Arrays.sort() method is part of the java.util.Arrays class. It can sort arrays of primitive types (such as int, double, char) and arrays of objects. When sorting arrays of objects, the elements must implement the Comparable interface.

The basic syntax for sorting an array of Comparable objects is:

Arrays.sort(arrayName);

Here, arrayName is the name of the array you want to sort.

3.2. Example: Sorting an Array of Integer Objects

Let’s start with a simple example of sorting an array of Integer objects:

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        Integer[] numbers = {5, 2, 8, 1, 9, 4};

        System.out.println("Before sorting: " + Arrays.toString(numbers));
        Arrays.sort(numbers);
        System.out.println("After sorting: " + Arrays.toString(numbers));
    }
}

Output:

Before sorting: [5, 2, 8, 1, 9, 4]
After sorting: [1, 2, 4, 5, 8, 9]

In this example, the Arrays.sort() method sorts the numbers array in ascending order based on the natural ordering of Integer objects.

3.3. Example: Sorting an Array of Custom Objects

Now, let’s sort an array of custom objects. Suppose you have a Student class that implements the Comparable interface:

class Student implements Comparable<student> {
    private String name;
    private int age;
    private double gpa;

    public Student(String name, int age, double gpa) {
        this.name = name;
        this.age = age;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getGpa() {
        return gpa;
    }

    @Override
    public int compareTo(Student other) {
        // Compare based on GPA
        return Double.compare(other.gpa, this.gpa); // Sort in descending order of GPA
    }

    @Override
    public String toString() {
        return name + " (Age: " + age + ", GPA: " + gpa + ")";
    }
}
</student>

In this example, the compareTo() method compares Student objects based on their GPA in descending order (highest GPA first).

3.4. Sorting the Array of Student Objects

You can now sort an array of Student objects using Arrays.sort():

import java.util.Arrays;

public class StudentArraySortExample {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Alice", 20, 3.8),
            new Student("Bob", 22, 3.5),
            new Student("Charlie", 21, 3.9)
        };

        System.out.println("Before sorting: " + Arrays.toString(students));
        Arrays.sort(students);
        System.out.println("After sorting: " + Arrays.toString(students));
    }
}

Output:

Before sorting: [Alice (Age: 20, GPA: 3.8), Bob (Age: 22, GPA: 3.5), Charlie (Age: 21, GPA: 3.9)]
After sorting: [Charlie (Age: 21, GPA: 3.9), Alice (Age: 20, GPA: 3.8), Bob (Age: 22, GPA: 3.5)]

The Arrays.sort() method sorts the students array based on the GPA, with the highest GPA appearing first.

3.5. Important Considerations

  • Null Values: If the array contains null values, the Arrays.sort() method will throw a NullPointerException. Ensure that the array does not contain null values before sorting.
  • Type Compatibility: Ensure that all elements in the array are of the same type and implement the Comparable interface. Otherwise, a ClassCastException may be thrown.
  • Consistency: The compareTo() method should be consistent with the equals() method. If a.equals(b) is true, then a.compareTo(b) should return 0.

3.6. Sorting a Portion of an Array

The Arrays.sort() method also allows you to sort a portion of an array. The syntax for this is:

Arrays.sort(arrayName, fromIndex, toIndex);

Here, fromIndex is the index of the first element to be sorted (inclusive), and toIndex is the index of the last element to be sorted (exclusive).

For example:

import java.util.Arrays;

public class PartialArraySortExample {
    public static void main(String[] args) {
        Integer[] numbers = {5, 2, 8, 1, 9, 4};

        System.out.println("Before sorting: " + Arrays.toString(numbers));
        Arrays.sort(numbers, 1, 5); // Sort from index 1 to 4
        System.out.println("After sorting: " + Arrays.toString(numbers));
    }
}

Output:

Before sorting: [5, 2, 8, 1, 9, 4]
After sorting: [5, 1, 2, 8, 9, 4]

In this example, only the elements from index 1 to 4 are sorted.

3.7. Using Comparable with Primitive Type Wrappers

Java provides wrapper classes for primitive types, such as Integer, Double, Character, etc., which implement the Comparable interface. You can directly use these wrapper classes to sort arrays of primitive types:

import java.util.Arrays;

public class PrimitiveWrapperSortExample {
    public static void main(String[] args) {
        Integer[] numbers = {5, 2, 8, 1, 9, 4};

        System.out.println("Before sorting: " + Arrays.toString(numbers));
        Arrays.sort(numbers);
        System.out.println("After sorting: " + Arrays.toString(numbers));
    }
}

Output:

Before sorting: [5, 2, 8, 1, 9, 4]
After sorting: [1, 2, 4, 5, 8, 9]

3.8. Sorting in Descending Order

To sort an array in descending order, you can either reverse the order of the sorted array or use a custom Comparator. Reversing the order of the sorted array can be done using a simple loop or the Collections.reverse() method if you convert the array to a list.

Here’s an example of reversing the order of the sorted array:

import java.util.Arrays;

public class ReverseArraySortExample {
    public static void main(String[] args) {
        Integer[] numbers = {5, 2, 8, 1, 9, 4};

        System.out.println("Before sorting: " + Arrays.toString(numbers));
        Arrays.sort(numbers);
        System.out.println("After sorting (ascending): " + Arrays.toString(numbers));

        // Reverse the array
        for (int i = 0, j = numbers.length - 1; i < j; i++, j--) {
            Integer temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }

        System.out.println("After sorting (descending): " + Arrays.toString(numbers));
    }
}

Output:

Before sorting: [5, 2, 8, 1, 9, 4]
After sorting (ascending): [1, 2, 4, 5, 8, 9]
After sorting (descending): [9, 8, 5, 4, 2, 1]

3.9. Conclusion

Sorting Java arrays using the Comparable interface is a fundamental skill for any Java developer. The Arrays.sort() method provides a simple and efficient way to sort arrays of objects based on their natural ordering. By understanding how to implement the Comparable interface and use the Arrays.sort() method, you can easily sort arrays of custom objects and primitive type wrappers in your Java programs.

4. TreeMap and Comparable for Sorted Maps

In Java, a TreeMap is a sorted map implementation that maintains its entries in ascending order, according to the natural ordering of its keys or by a Comparator provided at map creation time. When the keys of a TreeMap implement the Comparable interface, the map automatically sorts its entries based on the natural ordering of the keys. Let’s explore how to use TreeMap with Comparable for sorted maps.

4.1. Basic Usage of TreeMap

The TreeMap class is part of the java.util package. It implements the SortedMap interface, which extends the Map interface. The keys of a TreeMap must be comparable, either by implementing the Comparable interface or by providing a Comparator.

The basic syntax for creating a TreeMap is:

TreeMap<keyType, valueType> treeMap = new TreeMap<>();

Here, KeyType is the type of the keys, and ValueType is the type of the values.

4.2. Example: TreeMap with Integer Keys

Let’s start with a simple example of a TreeMap with Integer keys:

import java.util.TreeMap;

public class TreeMapIntegerExample {
    public static void main(String[] args) {
        TreeMap<integer, string> treeMap = new TreeMap<>();

        treeMap.put(3, "Three");
        treeMap.put(1, "One");
        treeMap.put(2, "Two");

        System.out.println("TreeMap: " + treeMap);
    }
}
</integer,>

Output:

TreeMap: {1=One, 2=Two, 3=Three}

In this example, the TreeMap automatically sorts the entries based on the natural ordering of the Integer keys.

4.3. Example: TreeMap with Custom Object Keys Implementing Comparable

Now, let’s use a custom object as the key in a TreeMap. Suppose you have a Product class that implements the Comparable interface:

class Product implements Comparable<product> {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public int compareTo(Product other) {
        // Compare based on price
        return Double.compare(this.price, other.price);
    }

    @Override
    public String toString() {
        return name + " (Price: " + price + ")";
    }
}
</product>

In this example, the compareTo() method compares Product objects based on their price.

4.4. Using Product as Keys in TreeMap

You can now use the Product class as the key in a TreeMap:

import java.util.TreeMap;

public class TreeMapProductExample {
    public static void main(String[] args) {
        TreeMap<product, string> treeMap = new TreeMap<>();

        treeMap.put(new Product("Laptop", 1200.0), "Electronics");
        treeMap.put(new Product("Book", 25.0), "Books");
        treeMap.put(new Product("Headphones", 100.0), "Electronics");

        System.out.println("TreeMap: " + treeMap);
    }
}
</product,>

Output:

TreeMap: [Book (Price: 25.0)=Books, Headphones (Price: 100.0)=Electronics, Laptop (Price: 1200.0)=Electronics]

The TreeMap sorts the entries based on the price of the Product keys.

4.5. Important Considerations

  • Comparable Implementation: The keys used in a TreeMap must implement the Comparable interface or a Comparator must be provided at the time of TreeMap creation. If neither of these conditions is met, a ClassCastException will be thrown when you try to insert elements into the map.
  • Null Keys: TreeMap does not allow null keys if the natural ordering is used (i.e., if the keys implement Comparable). If you try to insert a null key, a NullPointerException will be thrown.
  • Consistency: The compareTo() method should be consistent with the equals() method. If a.equals(b) is true, then a.compareTo(b) should return 0.

4.6. Using a Comparator with TreeMap

If you want to sort the TreeMap based on a different criteria than the natural ordering defined by the Comparable interface, you can provide a Comparator at the time of TreeMap creation.

For example, you can create a Comparator to sort Product objects based on their name:

import java.util.Comparator;

class ProductNameComparator implements Comparator<product> {
    @Override
    public int compare(Product p1, Product p2) {
        return p1.getName().compareTo(p2.getName());
    }
}
</product>

You can then use this Comparator when creating the TreeMap:

import java.util.TreeMap;

public class TreeMapComparatorExample {
    public static void main(String[] args) {
        TreeMap<product, string> treeMap = new TreeMap<>(new ProductNameComparator());

        treeMap.put(new Product("Laptop", 1200.0), "Electronics");
        treeMap.put(new Product("Book", 25.0), "Books");
        treeMap.put(new Product("Headphones", 100.0), "Electronics");

        System.out.println("TreeMap: " + treeMap);
    }
}
</product,>

Output:

TreeMap: [Book (Price: 25.0)=Books, Headphones (Price: 100.0)=Electronics, Laptop (Price: 1200.0)=Electronics]

In this example, the TreeMap sorts the entries based on the name of the Product keys, as defined by the ProductNameComparator.

4.7. Benefits of Using TreeMap

  • Sorted Order: TreeMap maintains its entries in a sorted order, which can be useful for tasks such as retrieving the smallest or largest key, iterating over the keys in sorted order, or performing range queries.
  • Efficient Retrieval: TreeMap provides efficient retrieval of elements, with a time complexity of O(log n) for most operations, where n is the number of entries in the map.
  • Flexibility: TreeMap allows you to define the sorting criteria using either the Comparable interface or a Comparator.

4.8. Conclusion

Using TreeMap with the Comparable interface is a powerful way to create sorted maps in Java. By implementing the Comparable interface in your key objects, you can ensure that the TreeMap automatically sorts its entries based on the natural ordering of the keys. Additionally, you can provide a Comparator to sort the TreeMap based on different criteria. Understanding how to use TreeMap and Comparable is essential for writing efficient and maintainable Java code that requires sorted maps.

5. TreeSet and Comparable for Sorted Sets

In Java, a TreeSet is a sorted set implementation that maintains its elements in ascending order, according to the natural ordering of its elements or by a Comparator provided at set creation time. When the elements of a TreeSet implement the Comparable interface, the set automatically sorts its elements based on the natural ordering. Let’s explore how to use TreeSet with Comparable for sorted sets.

5.1. Basic Usage of TreeSet

The TreeSet class is part of the java.util package. It implements the SortedSet interface, which extends the Set interface. The elements of a TreeSet must be comparable, either by implementing the Comparable interface or by providing a Comparator.

The basic syntax for creating a TreeSet is:

TreeSet<elementType> treeSet = new TreeSet<>();

Here, ElementType is the type of the elements in the set.

5.2. Example: TreeSet with Integer Elements

Let’s start with a simple example of a TreeSet with Integer elements:

import java.util.TreeSet;

public class TreeSetIntegerExample {
    public static void main(String[] args) {
        TreeSet<integer> treeSet = new TreeSet<>();

        treeSet.add(3);
        treeSet.add(1);
        treeSet.add(2);

        System.out.println("TreeSet: " + treeSet);
    }
}
</integer>

Output:

TreeSet: [1, 2, 3]

In this example, the TreeSet automatically sorts the elements based on the natural ordering of the Integer objects.

5.3. Example: TreeSet with Custom Object Elements Implementing Comparable

Now, let’s use a custom object as the element in a TreeSet. Suppose you have an Employee class that implements the Comparable interface:

class Employee implements Comparable<employee> {
    private String name;
    private int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    @Override
    public int compareTo(Employee other) {
        // Compare based on employee ID
        return Integer.compare(this.id, other.id);
    }

    @Override
    public String toString() {
        return name + " (ID: " + id + ")";
    }
}
</employee>

In this example, the compareTo() method compares Employee objects based on their employee ID.

5.4. Using Employee as Elements in TreeSet

You can now use the Employee class as the element in a TreeSet:

import java.util.TreeSet;

public class TreeSetEmployeeExample {
    public static void main(String[] args) {
        TreeSet<employee> treeSet = new TreeSet<>();

        treeSet.add(new Employee("Alice", 101));
        treeSet.add(new Employee("Bob", 100));
        treeSet.add(new Employee("Charlie", 102));

        System.out.println("TreeSet: " + treeSet);
    }
}
</employee>

Output:

TreeSet: [Bob (ID: 100), Alice (ID: 101), Charlie (ID: 102)]

The TreeSet sorts the elements based on the employee ID of the Employee objects.

5.5. Important Considerations

  • Comparable Implementation: The elements used in a TreeSet must implement the Comparable interface or a

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *