title: Comparables and Wilcard Generics
body: <p>Suppose I have the following class (for demonstration purposes)</p>
  
  <pre><code>package flourish.lang.data;
  public class Toyset implements Comparable&lt;Toyset&gt; {
      private Comparable&lt;?&gt;[] trains;
  
      @Override
      public int compareTo(Toyset o) {
          for (int i =0; i&lt;trains.length; i++) {
              if (trains[i].compareTo(o.trains[i]) &lt; 0)
                  return -1;
          }
          return 1;
       }  
  }
  </code></pre>
  
  <p>The compiler tells me</p>
  
  <blockquote>
    <p>"The method compareTo(capture#1-of ?) in the type <code>Comparable&lt;capture#1-of ?&gt;</code> is not applicable for the arguments (<code>Comparable&lt;capture#2-of ?&gt;</code>)"</p>
  </blockquote>
  
  <p>How can I deal with the fact that I want to put different <code>Comparables</code> into trains?
  Sure I could remove the parameters and go with raw types, but that seems like a little bit of a cop-out.</p>
  
  <p>EDIT:
  Perhaps the example I've given is a little obtuse. What I'm trying to understand is whether generics should always be used with <code>Comparables</code>. e.g. If the class of the object I want compare is not known until runtime:</p>
  
  <pre><code>public class ComparisonTool {
      public static int compareSomeObjects(final Class&lt;? extends Comparable&gt; clazz, final Object o1, final Object o2) {
          return clazz.cast(o1).compareTo(clazz.cast(o2));
      }
  
      public static void main(String[] args) {
          System.out.println(compareSomeObjects(Integer.class, new Integer(22), new Integer(33)));
      }
  }
  </code></pre>
  
  <p>If I replace <code>Comparable</code> with <code>Comparable&lt;?&gt;</code> then the compiler complains (as above) because the two cast operations are not guaranteed to be the same class (capture#1 of ? vs capture#2 of ?). On the other hand, I can't replace them with <code>Comparable&lt;Object&gt;</code> either, because then the call in <code>main()</code> doesn't match the method signature (i.e. <code>Integer</code> implements <code>Comparable&lt;Integer&gt;</code> and not <code>Comparable&lt;Object&gt;</code>. Using the raw type certainly 'works', but is this the right approach?</p>