๐ข Custom Class Example (`Book`): Let's define a `Book` class that implements `Comparable` to sort books by their title alphabetically.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Book implements Comparable<Book> {
private String title;
private String author;
private int publicationYear;
public Book(String title, String author, int publicationYear) {
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
}
public String getTitle() { return title; }
public String getAuthor() { return author; }
public int getPublicationYear() { return publicationYear; }
@Override
public int compareTo(Book other) {
// Natural ordering by title (alphabetical)
return this.title.compareTo(other.title);
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", year=" + publicationYear +
'}';
}
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979));
books.add(new Book("1984", "George Orwell", 1949));
books.add(new Book("Brave New World", "Aldous Huxley", 1932));
System.out.println("Books before sorting: " + books);
Collections.sort(books); // Sorts based on Book's natural ordering (by title)
System.out.println("Books after sorting: " + books);
}
}
Expected Output:
Books before sorting: [Book{title='The Hitchhiker's Guide to the Galaxy', author='Douglas Adams', year=1979}, Book{title='1984', author='George Orwell', year=1949}, Book{title='Brave New World', author='Aldous Huxley', year=1932}]
Books after sorting: [Book{title='1984', author='George Orwell', year=1949}, Book{title='Brave New World', author='Aldous Huxley', year=1932}, Book{title='The Hitchhiker's Guide to the Galaxy', author='Douglas Adams', year=1979}]