title: What is the alternative to Comparator<T> when using composition over inheritance?
body: <p>While refactoring a Java project to use composition and no inheritance, I have remaining a problem where polymorphic sorting of Collections was performed.</p>
  
  <p>Inheritance example:</p>
  
  <pre><code>public class AClass
  {
      private List&lt;OneClassOfManyThatRequireSortedInstances&gt; unsortedList;
  
      public List&lt;OneClassOfManyThatRequireSortedInstances&gt; getSortedList()
      {
          List&lt;OneClassOfManyThatRequireSortedInstances&gt; sortedList = new ArrayList(this.unsortedList);
          Collections.sort(sortedList, SuperClassOfManyThatRequireSortedInstances.orderComparator);
  
          return sortedList;
      }
  }
  </code></pre>
  
  <p>Now, after refactoring; classes <code>OneClassOfManyThatRequireSortedInstances</code> no longer inherit from abstract <code>SuperClassOfManyThatRequireSortedInstances</code> but <code>Collections.sort()</code> expects mutually comparable instances.</p>
  
  <p>What is the best way to refactor this?</p>
  
  <h3>Edit:</h3>
  
  <p>For completeness; I've added the Comparator implementation and further clarification of the problem.</p>
  
  <pre><code>public class SuperClassOfManyThatRequireSortedInstances
  {
      private int order;
  
      public static final Comparator&lt;SuperClassOfManyThatRequireSortedInstances&gt; orderComparator = new Comparator&lt;SuperClassOfManyThatRequireSortedInstances&gt;()
      {
          public int compare(SuperClassOfManyThatRequireSortedInstances o1, SuperClassOfManyThatRequireSortedInstances o2)
          {
              if ((o1 == null) &amp;&amp; (o2 == null))
              {
                  return 0;
              }
              if (o1 == null)
              {
                  return -1;
              }
              if (o2 == null)
              {
                  return 1;
              }
              return (new Integer(o1.getOrder()).compareTo(new Integer(o2
                  .getOrder())));
          }
      };
  
  
      public int getOrder()
      {
          return this.order;
      }
  
  
      public void setOrder(int order)
      {
          this.order = order;
      }
  }
  </code></pre>
  
  <p>The crux of the issue is that after refactoring to composition, <code>OneClassOfManyThatRequireSortedInstances</code> no longer <code>"is a"</code> <code>SuperClassOfManyThatRequireSortedInstances</code> and so the code is broken.</p>
  
  <p>Many classes such as <code>OneClassOfManyThatRequireSortedInstances</code> no longer have a common parent. So, the <code>Collections.sort()</code> can't be used across these classes with only a single implementation of <code>Comparator</code>.
  Classes such as <code>OneClassOfManyThatRequireSortedInstances</code> now instead have a <code>SuperClassOfManyThatRequireSortedInstances</code> member; a <code>"has a"</code> relationship. </p>