title: Comparable and Comparator contract with regards to null
body: <p><code>Comparable</code> contract specifies that <code>e.compareTo(null)</code> must throw <code>NullPointerException</code>.</p>
  
  <p>From <a href="http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html" rel="noreferrer">the API</a>:</p>
  
  <blockquote>
    <p>Note that <code>null</code> is not an instance of any class, and <code>e.compareTo(null)</code> should throw a <code>NullPointerException</code> even though <code>e.equals(null)</code> returns <code>false</code>.</p>
  </blockquote>
  
  <p>On the other hand, <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code> API</a> mentions nothing about what needs to happen when comparing <code>null</code>. Consider the following attempt of a generic method that takes a <code>Comparable</code>, and return a <code>Comparator</code> for it that puts <code>null</code> as the minimum element.</p>
  
  <pre><code>static &lt;T extends Comparable&lt;? super T&gt;&gt; Comparator&lt;T&gt; nullComparableComparator() {
     return new Comparator&lt;T&gt;() {
        @Override public int compare(T el1, T el2) {
           return
              el1 == null ? -1 :
              el2 == null ? +1 :
              el1.compareTo(el2);
        }
     };
  }
  </code></pre>
  
  <p>This allows us to do the following:</p>
  
  <pre><code>List&lt;Integer&gt; numbers = new ArrayList&lt;Integer&gt;(
     Arrays.asList(3, 2, 1, null, null, 0)
  );
  Comparator&lt;Integer&gt; numbersComp = nullComparableComparator();
  Collections.sort(numbers, numbersComp);
  System.out.println(numbers);
  // "[null, null, 0, 1, 2, 3]"
  
  List&lt;String&gt; names = new ArrayList&lt;String&gt;(
     Arrays.asList("Bob", null, "Alice", "Carol")
  );
  Comparator&lt;String&gt; namesComp = nullComparableComparator();
  Collections.sort(names, namesComp);
  System.out.println(names);
  // "[null, Alice, Bob, Carol]"
  </code></pre>
  
  <p>So the questions are:</p>
  
  <ul>
  <li>Is this an acceptable use of a <code>Comparator</code>, or is it violating an unwritten rule regarding comparing <code>null</code> and throwing <code>NullPointerException</code>?</li>
  <li>Is it ever a good idea to even have to sort a <code>List</code> containing <code>null</code> elements, or is that a sure sign of a design error?</li>
  </ul>