How can I define my own Comparable type so that it can be naturally sorted within a List?

Brandon Rohlfs

When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or some of the classes like String and Date. What the Comparable interface provides is a way for a class to be sorted by it's natural ordering. So what do we mean by natural ordering? Depending on the type wishing to be sorted the natural ordering can be different things. If we are sorting Strings the ordering is lexicographic or alphabetic if we are sorting Dates the ordering is chronological if we are sorting Integers the ordering is numerical.

Comparable only contains one method that needs to be implemented by the class wishing to be sorted naturally. Remember if you try and sort a list that contains elements that do not implement the Comparable interface then Collections.sort() will throw an exception specifically a ClassCastException.

public interface Comparable<T>{
  public int compareTo(T o); 
}
The following is a short example on how to implement the Comparable interface and use the compareTo(T o) method.
import java.util.*; 

public final class Alpha implements Comparable<Alpha>{
 public static void main(String[] args){
 List<Alpha> alpha = new ArrayList<Alpha>(); 
 alpha.add(new Alpha("z"));
 alpha.add(new Alpha("g")); 
 alpha.add(new Alpha("k"));   
 alpha.add(new Alpha("q")); 
 alpha.add(new Alpha("a"));
 alpha.add(new Alpha("b"));
 alpha.add(new Alpha("o")); 
 alpha.add(new Alpha("v")); 
 alpha.add(new Alpha("c"));
  
 Collections.sort(alpha); 
 System.out.println(alpha);
 }
 private String letter; 
 public Alpha(String letter){
  if(letter == null){throw new NullPointerException();}
   this.letter = letter; 
 }
 public String toString(){return letter;}
 public boolean equals(Alpha a){ 
  if(!(a instanceof Alpha))
   return false; 
   return letter.equals(a.letter);
 }
 public int compareTo(Alpha a){
  int i = letter.compareTo(a.letter);
  return i; 
 }
}
More complex examples might included sorting on multiple fields. Most things that you would have to sort probably have more then one part like a name for instance (First:Middle:Last) or maybe you have to sort in (Brand:Model) order.
import java.util.*; 

public final class Car implements Comparable<Car>{
 public static void main(String[] args){
 Car[] cararry = {new Car("Toyota","Celica"), new Car("Honda","Civic"),
  new Car("Ford","Mustang"), new Car("Lexus","ES"), new Car("Acura","Integra"),
  new Car("Honda","Accord"), new Car("Acura","RL"), new Car("Toyota","Avalon")
 };
 List<Car> car = Arrays.asList(cararry);  
 
 Collections.sort(car); 
 System.out.println(car);
 }
 private String brand;
 private String model;  
 public Car(String brand, String model){
  if(brand == null || model == null){throw new NullPointerException();}
   this.brand = brand; 
   this.model = model;  
 }
 public String toString(){return brand + " " + model;} 
 public boolean equals(Car car){ 
  if(!(car instanceof Car))
   return false; 
    boolean samebrand = brand.equals(car.brand);
    return samebrand != true ? samebrand: model.equals(car.model); 
 }
 public int compareTo(Car car){
  int i = brand.compareTo(car.brand);
  return(i != 0 ? i : model.compareTo(car.model));  
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact