Arrays
The Arrays class
Comparable interface
How to implement the Comparable interface
- Define the compareTo method. Then, the sort method of the Arrays class uses the compareTo method to sort an array of objects created from that class.
- The compareTo method must return -1 if the current object is less than the passed object, 0 if the objects are equal, and 1 if the current object is greater than the passed object.
The Comparable interface defined in the Java API
public interface Comparable { int compareTo(Object obj); }
An Item class that implements the Comparable interface
public class Item implements Comparable { private int number; private String description; public Item(int number, String description) { this.number = number; this.description = description; } public int getNumber() { return number; } public String getDescription() { return description; } public int compareTo(Object o) { Item i = (Item) o; if (this.getNumber() < i.getNumber()) return -1; if (this.getNumber() > i.getNumber()) return 1; return 0; } }
Code that sorts an array of Item objects
Item[] items = new Item[3]; items[0] = new Item(102, "Duct Tape"); items[1] = new Item(103, "Bailing Wire"); items[2] = new Item(101, "Chewing Gum"); Arrays.sort(items); for (Item i : items) System.out.println(i.getNumber() + ": " + i.getDescription());
The console output
101: Chewing Gum 102: Duct Tape 103: Bailing Wire