Sorting Objects with Comparable
Once you have implemented the Comparable
interface in your classes, you can use the sorting capabilities provided by the Java Collections Framework to sort arrays and collections of your objects.
Sorting Arrays
To sort an array of objects that implement the Comparable
interface, you can use the Arrays.sort()
method:
Person[] people = {
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 20)
};
Arrays.sort(people);
// people array is now sorted by age, then by name
Sorting Collections
To sort a collection of objects that implement the Comparable
interface, you can use the Collections.sort()
method:
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 25));
personList.add(new Person("Bob", 30));
personList.add(new Person("Charlie", 20));
Collections.sort(personList);
// personList is now sorted by age, then by name
Sorting with Comparator
If you need to sort your objects based on a different criteria than the natural ordering defined by the Comparable
interface, you can use a Comparator
instead:
Comparator<Person> byNameLength = (p1, p2) -> Integer.compare(p1.getName().length(), p2.getName().length());
personList.sort(byNameLength);
// personList is now sorted by the length of the name
By using the Comparable
interface and the sorting capabilities provided by the Java Collections Framework, you can easily sort your objects based on their natural ordering or custom criteria, making your code more efficient and maintainable.