Friday 8 April 2016

Effective Java Item 28: Generics Comparable

What's the benefit of using Comparable<? super T>?

   public static <T extends Comparable<T>> T max1 (List<T> list){  
     //implementation not import  
     return null;  
   }  
   public static <T extends Comparable<? super T>> T max2 (List<T> list){  
     //implementation not import  
     return null;  
   }  

The code below compiles fine.

 class Cat implements Comparable<Cat>{  
   @Override  
   public int compareTo(Cat o) {return 0;}  
   public static void main(String[] args){  
     List<Cat> cats = new ArrayList<>();  
     max1(cats);  
     max2(cats);  
   }  
 }  
However, if we make Cat extend Animal and allow it to compare with other animals....

 class Animal{}  
 class Cat extends Animal implements Comparable<Animal>{  
   @Override  
   public int compareTo(Animal o) {  
     return 0;  
   }  
 }  

max1() doesn't compile any more. Clearly, Comparable<? super T> is more flexible.

No comments:

Post a Comment