Arrays.sort for Object Arrays
What you'll learn: How to sort arrays of objects using Arrays.sort() when those objects have a natural ordering.
Sorting More Than Just Numbers
You've learned to sort primitive arrays (like int[]) with Arrays.sort(). But what about arrays of objects like String[] or custom objects? Java can sort these too—if the objects know how to compare themselves.
The Comparable Interface
For Arrays.sort() to work with object arrays, the objects must implement the Comparable interface. This interface requires a compareTo() method that defines the object's natural ordering—the default way objects of that type should be sorted.
Many built-in Java classes already implement Comparable:
Stringsorts alphabeticallyInteger,Doublesort numericallyLocalDatesorts chronologically
How It Works
When you call Arrays.sort() on an object array, Java uses each object's compareTo() method to determine order:
String[] names = {"Zara", "Alice", "Mike"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
// Output: [Alice, Mike, Zara]
The String class already knows how to compare itself alphabetically, so sorting "just works."
Think of It Like This
Imagine sorting books on a shelf. If each book could tell you whether it comes before or after another book (by title, author, or ISBN), you could easily arrange them. The Comparable interface gives objects that self-awareness.
What About Custom Objects?
If you try sorting an array of objects that don't implement Comparable, you'll get a runtime error. The objects need to define their natural ordering first—but that's a topic for later lessons.
Key Takeaway: Arrays.sort() works on object arrays when the objects implement Comparable and define their natural ordering through the compareTo() method.