<<< Example of search within unsorted array | Index | Arrays.sort >>> |
The Comparable interface is defined in the Java API as follows:
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;
}
// NOTE: @Override indicates programmer's intention to
// override a method declared in an interface or a superclass:
@Override
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;
}
}//class Item
<<< Example of search within unsorted array | Index | Arrays.sort >>> |