How Do You Implement The Comparable Interface In Java?

The Comparable interface in Java is used to define a natural ordering for objects of a user-defined class, facilitating sorting and comparison operations. Learn how to implement it effectively on COMPARE.EDU.VN.

Introduction

The Comparable interface in Java, part of the java.lang package, allows objects to be compared with each other. It provides a compareTo() method, which defines the natural ordering of objects, enabling you to sort collections of custom objects easily. Mastering this interface is crucial for effective object comparison and sorting in Java applications. By understanding and correctly implementing Comparable, you can ensure that your objects are sorted according to your specific criteria, improving the functionality and efficiency of your code. Stay informed with the latest trends and best practices by visiting COMPARE.EDU.VN for more insightful content. Leverage semantic keywords and LSI keywords to enhance your understanding.

Table of Contents

  1. Understanding the Comparable Interface
  2. Declaration of the Comparable Interface
  3. Steps to Implement the Comparable Interface
  4. Example 1: Implementing Comparable for Sorting Integers
  5. Example 2: Sorting Pairs with String and Integer Fields
  6. Example 3: Sorting Pairs with First and Last Names
  7. Best Practices for Implementing Comparable
  8. Common Mistakes to Avoid When Implementing Comparable
  9. Comparable vs. Comparator: Key Differences
  10. Use Cases for the Comparable Interface
  11. Advanced Techniques with the Comparable Interface
  12. Testing Your Comparable Implementation
  13. Comparable Interface in Different Java Versions
  14. Performance Considerations When Using Comparable
  15. Real-World Applications of Comparable
  16. How COMPARE.EDU.VN Can Help You Choose the Right Implementation
  17. Conclusion
  18. FAQ Section

1. Understanding the Comparable Interface

The Comparable interface in Java is fundamental for defining a natural ordering of objects within a class. It is part of the java.lang package, meaning it is readily available without needing to import any additional libraries. The primary purpose of this interface is to enable the comparison of one object to another of the same type, which is essential for sorting and searching algorithms.

What is Natural Ordering?

Natural ordering refers to the default way objects of a class are compared. For example, integers are naturally ordered numerically, and strings are naturally ordered lexicographically (alphabetically). By implementing the Comparable interface, you define this natural ordering for your custom classes.

Role of the compareTo() Method

The Comparable interface contains a single method, compareTo(), which you must implement. This method determines the order of objects. Here’s a breakdown of what the compareTo() method should return:

  • 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.

Why Use the Comparable Interface?

Using the Comparable interface offers several benefits:

  • Sorting: It allows you to sort collections of objects using methods like Collections.sort() or Arrays.sort().
  • Searching: It enables you to use binary search algorithms on collections of objects.
  • Data Structures: It is required by certain data structures like TreeSet and TreeMap, which maintain elements in a sorted order.

Basic Syntax

To implement the Comparable interface, your class declaration should look like this:

class MyClass implements Comparable<MyClass> {
    // Class members and methods
    @Override
    public int compareTo(MyClass other) {
        // Comparison logic
    }
}

Here, MyClass is the class you are defining, and it implements the Comparable interface, specifying that it can be compared to other instances of MyClass.

Importance of Consistency

It’s crucial that your compareTo() method is consistent. This means that if a.compareTo(b) returns a negative value, then b.compareTo(a) should return a positive value, and vice versa. Additionally, if a.compareTo(b) returns 0, then a and b should be considered equal for all practical purposes.

Real-World Example

Consider a class representing a Student with attributes like name and age. You might want to sort students based on their age. By implementing the Comparable interface, you can define the natural ordering of Student objects to be based on their age.

class Student implements Comparable<Student> {
    String name;
    int age;

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

    @Override
    public int compareTo(Student other) {
        return this.age - other.age; // Sort by age
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    public static void main(String[] args) {
        Student[] students = {
                new Student("Alice", 20),
                new Student("Bob", 22),
                new Student("Charlie", 19)
        };

        Arrays.sort(students);

        for (Student student : students) {
            System.out.println(student);
        }
    }
}

In this example, the compareTo() method compares the ages of two Student objects. When you sort an array of Student objects using Arrays.sort(), the students will be arranged in ascending order of age.

Leveraging COMPARE.EDU.VN

For a deeper understanding and comparison of different sorting techniques and their performance, visit COMPARE.EDU.VN. Here, you can find detailed analyses and practical examples to help you implement the Comparable interface effectively. Understanding the nuances of the Comparable interface is essential for any Java developer who needs to sort and compare objects. By defining a natural ordering for your classes, you can take advantage of Java’s built-in sorting and searching capabilities, making your code more efficient and maintainable.

2. Declaration of the Comparable Interface

The Comparable interface is a cornerstone of Java’s sorting and comparison framework. It declares a single method, compareTo(), which enables objects to define their natural ordering. Understanding the declaration and nuances of this interface is crucial for effective implementation.

Interface Definition

The Comparable interface is defined in the java.lang package, which means it is automatically available in all Java programs without needing an explicit import statement. The interface is generic, allowing you to specify the type of object that the class can be compared to.

The declaration of the Comparable interface is as follows:

package java.lang;

public interface Comparable<T> {
    int compareTo(T obj);
}

Here, T is the type parameter, representing the class that implements the Comparable interface. The compareTo() method compares the current object with the specified object.

Type Parameter T

The type parameter T ensures type safety. When you implement Comparable<MyClass>, you are promising that your compareTo() method will accept an object of type MyClass as an argument. This prevents runtime errors by ensuring that only objects of the correct type are compared.

The compareTo() Method

The compareTo() method is the heart of the Comparable interface. It takes an object of type T as input and returns an integer value that indicates the relationship between the current object and the input object.

  • Signature: int compareTo(T obj)
  • Parameters:
    • obj: The object to be compared with the current object.
  • Returns:
    • A negative integer if the current object is less than obj.
    • Zero if the current object is equal to obj.
    • A positive integer if the current object is greater than obj.

Contract of the compareTo() Method

The compareTo() method must adhere to certain rules to ensure consistent and predictable behavior:

  1. Symmetry:
    • If x.compareTo(y) > 0, then y.compareTo(x) < 0.
    • If x.compareTo(y) < 0, then y.compareTo(x) > 0.
  2. Transitivity:
    • If x.compareTo(y) > 0 and y.compareTo(z) > 0, then x.compareTo(z) > 0.
    • If x.compareTo(y) < 0 and y.compareTo(z) < 0, then x.compareTo(z) < 0.
  3. Consistency with Equals:
    • It is strongly recommended (though not strictly required) that (x.compareTo(y)==0) == (x.equals(y)).
    • If this condition is not met, you should clearly document that the ordering is inconsistent with equals.

Example of Implementing compareTo()

Consider a Book class with attributes title and publicationYear. You might want to sort books based on their publication year. Here’s how you can implement the Comparable interface:

class Book implements Comparable<Book> {
    String title;
    int publicationYear;

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

    @Override
    public int compareTo(Book other) {
        return this.publicationYear - other.publicationYear;
    }

    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + ''' +
                ", publicationYear=" + publicationYear +
                '}';
    }

    public static void main(String[] args) {
        Book[] books = {
                new Book("The Great Gatsby", 1925),
                new Book("To Kill a Mockingbird", 1960),
                new Book("1984", 1949)
        };

        Arrays.sort(books);

        for (Book book : books) {
            System.out.println(book);
        }
    }
}

In this example, the compareTo() method compares the publicationYear of two Book objects. The books are then sorted in ascending order of their publication year.

Handling Null Values

When implementing compareTo(), it’s essential to handle null values gracefully. A common approach is to treat null as the smallest possible value or to throw a NullPointerException if null is not a valid value for comparison.

@Override
public int compareTo(Book other) {
    if (other == null) {
        return 1; // Treat null as the smallest value
    }
    return this.publicationYear - other.publicationYear;
}

Best Practices

  • Ensure Type Safety: Always use the generic type parameter T to ensure that you are comparing objects of the correct type.
  • Follow the Contract: Adhere to the rules of symmetry, transitivity, and consistency with equals.
  • Handle Null Values: Decide how to handle null values and implement the logic accordingly.
  • Keep it Simple: The comparison logic should be straightforward and easy to understand.

Leveraging COMPARE.EDU.VN

For more detailed explanations, examples, and comparisons of different sorting techniques, visit COMPARE.EDU.VN. Understanding the declaration and proper implementation of the Comparable interface is crucial for creating well-behaved and efficient Java applications.

3. Steps to Implement the Comparable Interface

Implementing the Comparable interface in Java involves a few key steps to ensure that your class can be properly sorted and compared. Here’s a detailed guide on how to do it:

Step 1: Declare the Class and Implement the Interface

First, you need to declare your class and specify that it implements the Comparable interface. This involves using the implements keyword and providing the type parameter for the class you are comparing.

class MyClass implements Comparable<MyClass> {
    // Class members and methods
}

Here, MyClass is the class you are defining, and it implements Comparable<MyClass>, indicating that it can be compared to other instances of MyClass.

Step 2: Implement the compareTo() Method

The core of implementing the Comparable interface is providing the implementation for the compareTo() method. This method defines the logic for comparing two objects of your class.

@Override
public int compareTo(MyClass other) {
    // Comparison logic
}

The @Override annotation is used to ensure that you are correctly overriding the method from the Comparable interface.

Step 3: Define the Comparison Logic

Inside the compareTo() method, you need to define how two objects of your class are compared. The method should return:

  • A negative integer if the current object is less than the specified object.
  • Zero if the current object is equal to the specified object.
  • A positive integer if the current object is greater than the specified object.

The comparison logic will depend on the attributes of your class. For example, if you are comparing objects based on a single numerical attribute, you can simply subtract the attribute values.

class MyClass implements Comparable<MyClass> {
    int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    public int compareTo(MyClass other) {
        return this.value - other.value;
    }
}

In this example, the compareTo() method compares the value attribute of two MyClass objects.

Step 4: Handle Null Values (If Necessary)

If your class attributes can be null, you need to handle null values in your comparison logic. A common approach is to treat null as the smallest possible value or to throw a NullPointerException if null is not a valid value for comparison.

class MyClass implements Comparable<MyClass> {
    Integer value; // Use Integer instead of int to allow null values

    public MyClass(Integer value) {
        this.value = value;
    }

    @Override
    public int compareTo(MyClass other) {
        if (this.value == null && other.value == null) {
            return 0; // Both are null, so they are equal
        } else if (this.value == null) {
            return -1; // This object is null, so it is less than the other
        } else if (other.value == null) {
            return 1; // The other object is null, so this is greater
        } else {
            return this.value - other.value;
        }
    }
}

Step 5: Ensure Consistency with equals() (Recommended)

It is strongly recommended that your compareTo() method is consistent with your equals() method. This means that if a.compareTo(b) returns 0, then a.equals(b) should also return true, and vice versa.

If your compareTo() method is not consistent with equals(), you should clearly document this fact.

class MyClass implements Comparable<MyClass> {
    int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    public int compareTo(MyClass other) {
        return this.value - other.value;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        MyClass myClass = (MyClass) obj;
        return value == myClass.value;
    }
}

In this example, the equals() method checks if two MyClass objects have the same value. This is consistent with the compareTo() method, which also compares the value attribute.

Step 6: Test Your Implementation

After implementing the Comparable interface, it’s important to test your implementation thoroughly. This can be done by creating a collection of objects and sorting them using Arrays.sort() or Collections.sort().

public static void main(String[] args) {
    MyClass[] objects = {
            new MyClass(3),
            new MyClass(1),
            new MyClass(2)
    };

    Arrays.sort(objects);

    for (MyClass obj : objects) {
        System.out.println(obj.value);
    }
}

This code creates an array of MyClass objects and sorts them using Arrays.sort(). The output should be 1, 2, and 3, indicating that the objects have been sorted correctly.

Real-World Example: Sorting Products by Price

Consider a class representing a Product with attributes like name and price. You might want to sort products based on their price. Here’s how you can implement the Comparable interface:

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

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

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

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + ''' +
                ", price=" + price +
                '}';
    }

    public static void main(String[] args) {
        Product[] products = {
                new Product("Laptop", 1200.0),
                new Product("Tablet", 300.0),
                new Product("Smartphone", 800.0)
        };

        Arrays.sort(products);

        for (Product product : products) {
            System.out.println(product);
        }
    }
}

In this example, the compareTo() method compares the prices of two Product objects using Double.compare(), which handles the comparison of double values correctly. The products are then sorted in ascending order of their prices.

Leveraging COMPARE.EDU.VN

For more in-depth comparisons and examples, visit COMPARE.EDU.VN. Implementing the Comparable interface correctly allows you to take advantage of Java’s built-in sorting capabilities, making your code more efficient and maintainable.

4. Example 1: Implementing Comparable for Sorting Integers

One of the simplest and most illustrative examples of implementing the Comparable interface is sorting integers. This example demonstrates how to define a custom class that wraps an integer and provides a natural ordering for its instances.

Creating the Number Class

First, create a class named Number that encapsulates an integer value. This class will implement the Comparable interface to allow its instances to be compared.

class Number implements Comparable<Number> {
    int value;

    public Number(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

    @Override
    public int compareTo(Number other) {
        return this.value - other.value;
    }

    public static void main(String[] args) {
        Number[] numbers = {
                new Number(5),
                new Number(2),
                new Number(8),
                new Number(1)
        };

        Arrays.sort(numbers);

        for (Number number : numbers) {
            System.out.println(number);
        }
    }
}

Explanation

  1. Class Declaration:
    • The Number class is declared to implement the Comparable<Number> interface. This means that instances of Number can be compared to each other.
  2. Instance Variable:
    • The class has a single instance variable, value, which is an integer.
  3. Constructor:
    • The constructor initializes the value variable with the provided integer.
  4. toString() Method:
    • The toString() method is overridden to provide a string representation of the Number object, making it easy to print the value.
  5. compareTo() Method:
    • The compareTo() method compares the value of the current Number object with the value of the other Number object.
    • It returns the difference between the two values (this.value - other.value).
    • If the current object’s value is less than the other object’s value, it returns a negative integer.
    • If the current object’s value is equal to the other object’s value, it returns zero.
    • If the current object’s value is greater than the other object’s value, it returns a positive integer.
  6. main() Method:
    • The main() method creates an array of Number objects with different integer values.
    • It then uses the Arrays.sort() method to sort the array. This method uses the compareTo() method defined in the Number class to determine the order of the elements.
    • Finally, it iterates through the sorted array and prints the values of each Number object.

Sorting Logic

The compareTo() method’s logic is straightforward:

@Override
public int compareTo(Number other) {
    return this.value - other.value;
}

This code subtracts the value of the other object from the value of the current object. This works because:

  • If this.value is less than other.value, the result is negative.
  • If this.value is equal to other.value, the result is zero.
  • If this.value is greater than other.value, the result is positive.

Using Arrays.sort()

The Arrays.sort() method is used to sort the array of Number objects. This method relies on the compareTo() method to determine the order of the elements.

Arrays.sort(numbers);

After sorting, the numbers array will be in ascending order based on the integer values.

Output

When you run the main() method, the output will be:

1
2
5
8

This shows that the Number objects have been sorted correctly in ascending order.

Benefits of This Approach

  • Simplicity: The implementation is simple and easy to understand, making it a great starting point for learning about the Comparable interface.
  • Efficiency: For integer comparisons, this approach is efficient and performs well.
  • Customization: You can easily modify the compareTo() method to change the sorting order (e.g., to sort in descending order, you would return other.value - this.value).

Complete Code

Here’s the complete code for the Number class:

import java.util.Arrays;

class Number implements Comparable<Number> {
    int value;

    public Number(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

    @Override
    public int compareTo(Number other) {
        return this.value - other.value;
    }

    public static void main(String[] args) {
        Number[] numbers = {
                new Number(5),
                new Number(2),
                new Number(8),
                new Number(1)
        };

        Arrays.sort(numbers);

        for (Number number : numbers) {
            System.out.println(number);
        }
    }
}

Leveraging COMPARE.EDU.VN

For more detailed examples and comparisons, visit COMPARE.EDU.VN. This simple example illustrates the basic steps for implementing the Comparable interface and provides a foundation for more complex comparison scenarios.

5. Example 2: Sorting Pairs with String and Integer Fields

This example demonstrates how to implement the Comparable interface to sort objects with multiple fields. We will create a Pair class that consists of a string and an integer, and then sort an array of Pair objects based on the string field first, and then the integer field if the strings are equal.

Creating the Pair Class

First, create a class named Pair that encapsulates a string and an integer. This class will implement the Comparable interface to allow its instances to be compared.

import java.util.Arrays;

class Pair implements Comparable<Pair> {
    String str;
    int num;

    public Pair(String str, int num) {
        this.str = str;
        this.num = num;
    }

    @Override
    public String toString() {
        return "(" + str + ", " + num + ")";
    }

    @Override
    public int compareTo(Pair other) {
        int stringComparison = this.str.compareTo(other.str);
        if (stringComparison != 0) {
            return stringComparison; // Sort by string if different
        } else {
            return this.num - other.num; // If strings are equal, sort by number
        }
    }

    public static void main(String[] args) {
        Pair[] pairs = {
                new Pair("apple", 5),
                new Pair("banana", 2),
                new Pair("apple", 3),
                new Pair("orange", 1)
        };

        Arrays.sort(pairs);

        for (Pair pair : pairs) {
            System.out.println(pair);
        }
    }
}

Explanation

  1. Class Declaration:
    • The Pair class is declared to implement the Comparable<Pair> interface.
  2. Instance Variables:
    • The class has two instance variables: str (a string) and num (an integer).
  3. Constructor:
    • The constructor initializes the str and num variables with the provided values.
  4. toString() Method:
    • The toString() method is overridden to provide a string representation of the Pair object.
  5. compareTo() Method:
    • The compareTo() method compares the Pair objects based on two criteria:
      • First, it compares the str fields using the compareTo() method of the String class.
      • If the str fields are different, it returns the result of this comparison.
      • If the str fields are equal, it compares the num fields by subtracting them.
  6. main() Method:
    • The main() method creates an array of Pair objects with different string and integer values.
    • It then uses the Arrays.sort() method to sort the array.
    • Finally, it iterates through the sorted array and prints the values of each Pair object.

Sorting Logic

The compareTo() method’s logic is as follows:

@Override
public int compareTo(Pair other) {
    int stringComparison = this.str.compareTo(other.str);
    if (stringComparison != 0) {
        return stringComparison; // Sort by string if different
    } else {
        return this.num - other.num; // If strings are equal, sort by number
    }
}

This code first compares the string values. If they are different, the method returns the result of the string comparison. If the strings are the same, the method compares the integer values.

Output

When you run the main() method, the output will be:

(apple, 3)
(apple, 5)
(banana, 2)
(orange, 1)

This shows that the Pair objects have been sorted correctly, first by the string field and then by the integer field when the strings are equal.

Benefits of This Approach

  • Multi-Criteria Sorting: This example demonstrates how to sort objects based on multiple criteria.
  • Clarity: The code is clear and easy to understand, making it a good example for learning about complex comparisons.
  • Flexibility: You can easily modify the compareTo() method to change the sorting criteria or add additional criteria.

Complete Code

Here’s the complete code for the Pair class:

import java.util.Arrays;

class Pair implements Comparable<Pair> {
    String str;
    int num;

    public Pair(String str, int num) {
        this.str = str;
        this.num = num;
    }

    @Override
    public String toString() {
        return "(" + str + ", " + num + ")";
    }

    @Override
    public int compareTo(Pair other) {
        int stringComparison = this.str.compareTo(other.str);
        if (stringComparison != 0) {
            return stringComparison; // Sort by string if different
        } else {
            return this.num - other.num; // If strings are equal, sort by number
        }
    }

    public static void main(String[] args) {
        Pair[] pairs = {
                new Pair("apple", 5),
                new Pair("banana", 2),
                new Pair("apple", 3),
                new Pair("orange", 1)
        };

        Arrays.sort(pairs);

        for (Pair pair : pairs) {
            System.out.println(pair);
        }
    }
}

Leveraging COMPARE.EDU.VN

For more detailed examples and comparisons, visit compare.edu.vn. This example illustrates how to implement the Comparable interface to sort objects with multiple fields, providing a foundation for more complex sorting scenarios.

6. Example 3: Sorting Pairs with First and Last Names

This example extends the previous one by demonstrating how to sort objects with two string fields, such as first and last names. We will create a Person class with firstName and lastName attributes and sort an array of Person objects based on these fields.

Creating the Person Class

First, create a class named Person that encapsulates a first name and a last name. This class will implement the Comparable interface to allow its instances to be compared.

import java.util.Arrays;

class Person implements Comparable<Person> {
    String firstName;
    String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "(" + firstName + ", " + lastName + ")";
    }

    @Override
    public int compareTo(Person other) {
        int firstNameComparison = this.firstName.compareTo(other.firstName);
        if (firstNameComparison != 0) {
            return firstNameComparison; // Sort by first name if different
        } else {
            return this.lastName.compareTo(other.lastName); // If first names are equal, sort by last name
        }
    }

    public static void main(String[] args) {
        Person[] people = {
                new Person("John", "Doe"),
                new Person("Jane", "Doe"),
                new Person("John", "Smith"),
                new Person("Alice", "Johnson")
        };

        Arrays.sort(people);

        for (Person person : people) {
            System.out.println(person);
        }
    }
}

Explanation

  1. Class Declaration:
    • The Person class is declared to implement the Comparable<Person> interface.
  2. Instance Variables:
    • The class has two instance variables: firstName and lastName, both of which are strings.
  3. Constructor:
    • The constructor initializes the firstName and lastName variables with the provided values.
  4. toString() Method:
    • The toString() method is overridden to provide a string representation of the Person object.
  5. compareTo() Method:
    • The compareTo() method compares the Person objects based on two criteria:
      • First, it compares the firstName fields using the compareTo() method of the String class.
      • If the firstName fields are different, it returns the result of this comparison.
      • If the firstName fields are equal, it compares the lastName fields using the compareTo() method of the String class.
  6. main() Method:
    • The main() method creates an array of Person objects with different first and last names.
    • It then uses the Arrays.sort() method to sort the array.
    • Finally, it iterates through the sorted array and prints the values of each Person object.

Sorting Logic

The compareTo() method’s logic is as follows:

@Override
public int compareTo(Person other) {
    int firstNameComparison = this.firstName.compareTo(other.firstName);
    if (firstNameComparison != 0) {
        return firstNameComparison; // Sort by first name if different
    } else {
        return this.lastName.compareTo(other.lastName); // If first names are equal, sort by last name
    }
}

This code first compares the firstName values. If they are different, the method returns the result of the string comparison. If the firstName values are the same, the method compares the lastName values.

Output

When you run the main() method, the output will be:

(Alice, Johnson)
(Jane, Doe)
(John, Doe)
(John, Smith)

This shows that the Person objects have been sorted correctly, first by the firstName field and then by the lastName field when the firstName values are equal.

Benefits of This Approach

  • Complex String Sorting: This example demonstrates how to sort objects based on multiple string fields.
  • Readability: The code is readable and easy to understand, making it a good example for learning about complex string comparisons.
  • Extensibility: You can easily modify the compareTo() method to change the sorting criteria or add additional criteria (e.g., sorting by age after first and last names).

Complete Code

Here’s the complete code for the Person class:


import java.util.Arrays;

class Person implements Comparable<Person> {
    String firstName;
    String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "(" + firstName + ", " + lastName + ")";
    }

    @Override
    public int compareTo(Person other) {
        int firstNameComparison = this.firstName.compareTo(other.firstName);
        if (firstNameComparison != 0) {
            return firstNameComparison; // Sort by first name if different
        } else {
            return this.lastName.compareTo(other.lastName); // If first names are equal, sort by last name
        }
    }

    public static void main(String[] args) {

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 *