title: How to sort a list of generic types in Java
body: <p>I have a set of classes that all share some common attributes, so I made them all extend a common base class, <code>BaseEntity</code>.  So I have, for example <code>Foo extends BaseEntity</code> and <code>Bar extends BaseEntity</code>.</p>
  
  <p>I also want lists of these <code>Foo</code> and <code>Bar</code> objects to be sortable, so I have implemented <code>Comparable</code>.  I have the classes defined as <code>Foo extends BaseEntity implements Comparable&lt;Foo&gt;</code> and <code>Bar extends BaseEntity implements Comparable&lt;Bar&gt;</code>, and sorting of lists of <code>Foo</code>s or <code>Bar</code>s works as expected - and, of course, the details of the sorting are different in the different subclasses.  But I can't work out how to make my sorting work when I don't know in advance whether I'll have <code>Foo</code>s or <code>Bar</code>s.  This code, for example,  fails to compile:</p>
  
  <pre><code>public class UtilityClass&lt;T extends BaseEntity&gt; {
  
    ...bunch of stuff...
  
    List&lt;T&gt; values;
  
    public List&lt;T&gt; sort() {
      Collections.sort(values);
      return values;
    }
  
    ...more methods...
  }
  </code></pre>
  
  <p>with the error message <code>Bound mismatch: The generic method sort(List&lt;T&gt;) of type Collections is not applicable for the arguments (List&lt;T&gt;). The inferred type T is not a valid substitute for the bounded parameter &lt;T extends Comparable&lt;? super T&gt;&gt;</code></p>
  
  <p>I think the problem is that I am attempting to sort a list of <code>BaseEntity</code> objects, and <code>BaseEntity</code> itself doesn't implement <code>Comparable</code>.  But now I face a problem: the only sensible thing to make <code>BaseEntity</code> objects comparable to is other <code>BaseEntity</code> objects, but when I add <code>implements Comparable&lt;BaseEntity&gt;</code> to <code>BaseEntity</code>, the compiler tells me that I've got problems now because my <code>Foo</code> class is trying to implement both <code>Comparable&lt;BaseEntity&gt;</code> and <code>Comparable&lt;Foo&gt;</code>, which evidently is not allowed.</p>
  
  <p>I know I could sidestep this issue by dropping the <code>implements Comparable&lt;Foo&gt;</code> and just implementing <code>Comparable&lt;BaseEntity&gt;</code>, but then my <code>compareTo</code> methods will have to do ugly casting, and I thought that was exactly the sort of problem using generics was supposed to avoid.</p>
  
  <p>What I really want to do is specify in the signature of <code>BaseEntity</code> that all its subclasses will be <code>Comparable</code>, but only to instances of the same subclass.  </p>
  
  <p>Any assistance gratefully received.  Thanks!</p>