<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <title>java | Two 〈Foo〉s Walk into a 〈Bar〉</title>
  
  <updated>2009-08-22T17:59:00-05:00</updated>
  <author>
    <name>Chris Povirk</name>
    <email>beigetangerine@gmail.com</email>
    <uri>http://twofoos.org/</uri>
  </author>
  <link rel="alternate" type="application/xhtml+xml" hreflang="en" href="http://twofoos.org/tag/java/"/>
  <link rel="self" type="application/atom+xml" href="http://twofoos.org/tag/java/feed/"/>
  <rights>Copyright © 2003–2015 Chris Povirk.  All Rights Reserved.</rights>
  <id>http://twofoos.org/</id>
  <generator uri="http://twofoos.org/content/splat/" version="1.0">SPLAT</generator>
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
<entry>
    <updated>2009-08-22T17:59:00-05:00</updated>
    <summary>
            New: A small oversight and a big puzzler.</summary>
    <title type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">Two Java Type‐System Holes</div>
    </title>
    <link rel="alternate" type="application/xhtml+xml" href="http://twofoos.org/content/java-type-system-holes/#update_2009-08-22T17:59:00-05:00"/>
    <id>http://twofoos.org/content/java-type-system-holes/#update_2009-08-22T17:59:00-05:00</id>
    <category term="java"/>
    <content type="xhtml" xml:base="http://twofoos.org/">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <strong>initial posting</strong>
        <div>

    <div>
      <p>That is, two bugs in the language specification that allow a program to compile without warnings but to produce a <code>ClassCastException</code> at runtime on a line with no explicit cast.</p>
    </div>

    <xhtml:h3>Cast to Inner Class of Generic Type</xhtml:h3>
    <div>

    <xhtml:h4>Code</xhtml:h4>
    <div>
<blockquote><pre>class Outer&lt;E&gt; {
  Inner inner;

  class Inner {
    E e;

    E getOtherElement(Object other) {
      if (!(other instanceof Outer.Inner)) {
        throw new IllegalArgumentException(String.valueOf(other));
      }

      Inner that = (Inner) other;
      return that.e;
    }
  }

  public static void main(String[] args) {
    Outer&lt;String&gt; s = new Outer&lt;String&gt;();
    s.inner = s.new Inner();
    s.inner.e = "hello";

    Outer&lt;Integer&gt; i = new Outer&lt;Integer&gt;();
    i.inner = i.new Inner();
    i.inner.e = 1234;

    String producesClassCast = s.inner.getOtherElement(i.inner);
  }
}
</pre></blockquote>
    </div>

    <xhtml:h4>Output</xhtml:h4>
    <div>

<blockquote><pre>Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
  at Outer.main(Outer.java:26)</pre></blockquote>

    </div>

    <xhtml:h4>Explanation</xhtml:h4>
    <div>

<p>The Java language specification lacks rules about casts to inner classes.  Commonly used versions of javac happen to allow us to cast to <code>Inner</code> — that is, to cast to <code>Outer&lt;E&gt;.Inner</code> — without a warning.  <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6665356">The more honest version of the cast, <code>(Outer&lt;E&gt;.Inner)</code>, ought likewise to be permitted with a warning; it's rejected outright.</a></p>

<p>This subtle interaction between generics and inner classes pales in comparison to...</p>

    </div>

    </div>

    <xhtml:h3>Generic "Overrides" of Static Methods</xhtml:h3>
    <div>
    <xhtml:h4>Code</xhtml:h4>
    <div>
<blockquote><pre>import java.util.HashSet;
import static java.util.Collections.singleton;

class Printer {
  static &lt;E&gt; void print(Iterable&lt;E&gt; input) {
    for (E e : input) {
      System.out.println("Unsorted " + e);
    }
  }
}

class SortedPrinter extends Printer {
  static &lt;E extends Comparable&lt;? super E&gt;&gt; void print(Iterable&lt;E&gt; input) {
    for (E e : input) {
      System.out.println("Sorted " + e);
    }
  }
}

class Caller {
  public static void main(String[] args) {
    SortedPrinter.print(singleton(1));
    SortedPrinter.print(singleton(null));
    SortedPrinter.print(singleton(new HashSet&lt;Object&gt;()));
  }
}</pre></blockquote>
    </div>
    <xhtml:h4>Output</xhtml:h4>
    <div>

<blockquote><pre>Sorted 1
Sorted null
Exception in thread "main" java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.Comparable
  at SortedPrinter.print(Caller.java:14)
  at Caller.main(Caller.java:24)</pre></blockquote>

    </div>
    <xhtml:h4>Explanation</xhtml:h4>
    <div>

<p>You need two obscure pieces of knowledge to understand this one:</p>
<ol>
  <li>
    At runtime, methods are identified by these four pieces of information:
    <ul>
      <li>return type</li>
      <li>class name</li>
      <li>method name</li>
      <li>argument types</li>
    </ul>

    (Note the absence of anything related to type parameters.)
  </li>

  <li style="margin-top: 2em;">
    Indirect references to static methods are compiled oddly:

<blockquote><pre>class Base {
  static void foo() {}
}

class Derived extends Base {
}</pre></blockquote>

    The bytecode for a call to <code>Derived.foo()</code> is "<code>void Derived.foo()</code>,"
    not "<code>void Base.foo()</code>."  The VM knows to look for the method first in <code>Derived</code>
    and then in <code>Base</code>.
  </li>
</ol>

<p>
    So:
    The compiler can see that <code>Collection&lt;HashSet&lt;Object&gt;&gt;</code> does not
    implement <code>Comparable</code>.  Thus, it chooses the more general "inherited" version <code>&lt;E&gt;
    print(Iterable&lt;E&gt;)</code> over the restricted version <code>&lt;E extends Comparable&lt;? super E&gt;&gt;
    print(Iterable&lt;E&gt;)</code>.  Nevertheless, per point #2 above, the bytecode it produces still reads "<code>void
    SortedPrinter.print(Iterable)</code>."
</p>

<p>
    The VM sees "<code>void SortedPrinter.print(Iterable)</code>" and begins its search for <code>void print(Iterable)</code> in
    <code>SortedPrinter</code>.  <code>SortedPrinter</code> has exactly such a method.  The fact that it requires
    its input to be <code>Comparable</code> is unavailable at runtime.  The VM chooses that method.
</p>

<p>
    Thus, all three "<code>SortedPrinter.print()</code>" calls <strong>end up really calling
    <code>SortedPrinter.print()</code>, even though the compiler/IDE believes it is
    compiling a call to <code>Printer.print()</code></strong> in the HashSet case.  At runtime,
    <code>SortedPrinter.print()</code> implicitly casts each element of its input to
    <code>Comparable</code> ("<code>for (E e : input)</code>"), and the failure to cast <code>HashSet</code> gives
    us a <code>ClassCastException</code>.
</p>

    </div>
    <xhtml:h4>More Fun</xhtml:h4>
    <div>

    <p>This is a hole in the type system, but the fun doesn't stop there.  By adding method X, I can cause a call to method Y to become a call to method Z:</p>

<blockquote><pre>import java.util.HashSet;
import static java.util.Collections.singleton;

class Base {
  static &lt;E&gt; Object count(Iterable&lt;E&gt; input) {
    System.out.println("Base");
    int count = 0;
    for (E e : input) {
      count++;
    }
    return count;
  }
}

class Sub extends Base {
/*  static &lt;E&gt; Integer count(Iterable&lt;E&gt; input) {
    System.out.println("Sub");
    int count = 0;
    for (E e : input) {
      count++;
    }
    return count;
  }*/
}

class Subsub extends Sub {
  static &lt;E extends Comparable&lt;? super E&gt;&gt; Integer count(Iterable&lt;E&gt; input) {
    System.out.println("Subsub");
    int count = 0;
    for (E e : input) {
      count++;
    }
    return count;
  }
}

class Caller2 {
  public static void main(String[] args) {
    Subsub.count(singleton(1));
    Subsub.count(singleton(null));
    Subsub.count(singleton(new HashSet&lt;Object&gt;()));
  }
}</pre></blockquote>

<p>With <code>Sub.count()</code> commented out, we get:</p>

<blockquote><pre>Subsub
Base
Base</pre></blockquote>

<p>With <code>Sub.count()</code> restored, we get:</p>

<blockquote><pre>Subsub
Subsub
Subsub
&lt;the ClassCastException&gt;</pre></blockquote>

<p>Notice that <strong>in no case is <code>Sub.count()</code> itself called.  Its mere presence affects the behavior of the program.</strong></p>

<p>Why? The existence of <code>Sub.count()</code> makes the compiler write "<code>Integer Subsub.count()</code>" instead of "<code>Object Subsub.count()</code>."  At runtime, the former resolves to <code>Subsub.count()</code>; the latter, to <code>Base.count()</code>.</p>

<p>If you do want <code>Sub.count()</code> to be called, you must change its return type to <code>Object</code>.  Then we get:</p>

<blockquote><pre>Subsub
Sub
Sub</pre></blockquote>

<p>Changing the method's return type again changes which method is called.  The first method the compiler finds when looking for an appropriate <code>Subsub.count()</code> is still <code>Sub.count()</code>, but now it writes "<code>Object Subsub.count()</code>" instead of "<code>Integer Subsub.count()</code>."  At runtime, the former resolves to the appropriate method.</p>

    </div>

    <xhtml:h4>Lessons</xhtml:h4>
    <div>

    <p>First, the controversial part: When a compiler identifies a call to method X, it should produce code that calls method X, not hypothetical method Y.</p>

    <p>Second, programmers should generally avoid "overriding" static methods, most of all when type parameters are involved.  <code>&lt;E extends Comparable&lt;? super E&gt;&gt; ImmutableSortedSet.of(E)</code> and its superclass's <code>&lt;E&gt; ImmutableSet.of(E)</code> do not play nicely together.  Expect some gymnastics in <a href="http://google-collections.googlecode.com/svn/trunk/src/com/google/common/collect/ImmutableSortedSet.java">the <code>ImmutableSortedSet</code> code</a> next release.</p>

    </div>

    </div>

  </div>
      </div>
    </content>
  </entry><entry>
    <updated>2009-08-22T17:38:00-05:00</updated>
    <summary>
            Update: significantly rewritten</summary>
    <title type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">Static Factory Methods</div>
    </title>
    <link rel="alternate" type="application/xhtml+xml" href="http://twofoos.org/content/static-factory-methods/#update_2009-08-22T17:38:00-05:00"/>
    <id>http://twofoos.org/content/static-factory-methods/#update_2009-08-22T17:38:00-05:00</id>
    <category term="effective-java"/>
    <category term="java"/>
    <content type="xhtml" xml:base="http://twofoos.org/">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <strong>significantly rewritten</strong>
        <div>

    <xhtml:h3>Book Summary</xhtml:h3>
    <div>
      <p>Static factory methods can:</p>
      <ul>
        <li>have names</li>
        <li>control when new instances are created</li>
        <li>return any subtype of their return type</li>
        <li>reduce the need to specify type parameters</li>
      </ul>
    </div>

    <xhtml:h3>Additional Points</xhtml:h3>
    <div>

    <p>Static factory methods can assist in safe publication and can allow for selective type bounds.</p>

      <xhtml:h4>Safe Publication</xhtml:h4>
      <div>

        <p>Sometimes you want to create an object and publish a reference to it at the same time.  Sometimes you publish the reference where other threads can see it.  The obvious approach is to handle it all in the constructor:</p>
<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;

  public Request(Query query, User user) {
    this.query = query;
    this.user = user;

    sampleRequest = this;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Notice that <code>sampleRequest</code> is not declared <code>volatile</code>.  The intent is to give up the guarantee that all threads will see the most recent value in favor of the speed of a non‐volatile write.  And it would work if only the code were slightly different:</p>

<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;
<ins style="display: inline; font-weight: bold;">
  public static Request create(Query query, User user) {
    Request request = new Request(query, user);
    sampleRequest = request;
    return request;
  }

  private</ins> Request(Query query, User user) {
    this.query = query;
    this.user = user;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Readers of an object published by the former code can behave nondeterministically.  But the latter code, by waiting until after the constructor to publish the reference (and by containing no non‐final fields), takes advantage of a feature of the memory model: the end‐of‐constructor "freeze."  This freeze ensures that the object appears fully initialized (and thus immutable) to other threads.  <a href="http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html">Read Jeremy Manson's article on immutability</a>, and see also <a href="http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1218588162&amp;sr=8-1">Java Concurrency in Practice</a> pg. 41–42.</p>

        <p>What does this esoteric knowledge gain you?  Very little.  The reason is that examples like the above are rare.  In most cases, the act of publishing the reference is a <code>volatile</code> write or another synchronization action, such as adding the reference to a thread‐safe list of listeners.  Such actions guarantee that all steps performed before the publishing step are visible to all threads reading the reference.  The end‐of‐constructor freeze is superfluous.</p>

        <p>All this said, if you depend on others to write defensive code and they depend on you, you'll have problems.  Incomplete object initialization can be a security vulnerability:  An uninitialized "immutable" object might appear to contain an innocuous request during security checks, only to transform into a malicious one before execution.  <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370">Maybe spawning 0 processes is acceptable but 1,000,000 is not, or maybe 0 is a valid seed in a crypto algorithm but 1,000,000 is not.</a></p>

      </div>

      <xhtml:h4>Selective Type Bounds</xhtml:h4>
      <div>

        <xhtml:h5>The Problem</xhtml:h5>
        <div>

          <p>
          When parameterizing a class, I can choose to set bounds on the type parameter.  For example, <code>EnumSet</code> has type parameter <code>&lt;E extends Enum&lt;E&gt;&gt;</code>.  Or I can leave it unbounded: <code>HashSet</code> has type parameter <code>E</code>.
          </p>
          
          <p>
          Bounded or unbounded: What other options do I need?  Consider <code>TreeSet</code>.  <code>TreeSet</code> instances divide into two groups: those with a <code>Comparator</code> and those without.  When the caller provides a <code>Comparator</code>, the <code>TreeSet</code> can contain any kind of element supported by the <code>Comparator</code>.  Since I can define a <code>Comparator</code> for any type that I like, I can create a <code>TreeSet&lt;List&gt;</code>, a <code>TreeSet&lt;Rectangle&gt;</code>, or any other type, so long as I provide an appropriate <code>Comparator</code>.  On the other hand, when the caller does not provide a <code>Comparator</code>, the <code>TreeSet</code> can only contain elements that implement <code>Comparable</code> (specifically, elements that are <code>Comparable</code> to one another).  A <code>TreeSet&lt;List&gt;</code> without a <code>Comparator</code> will throw exceptions when it is used.
          </p>

          <p>
          The class's type parameter alone cannot provide us with the flexibility to solve this problem.  The result is two kinds of <code>TreeSet</code> constructors.  The first takes a <code>Comparator</code>.  As it should, it allows the caller to fill in any type for the type parameter, provided that it's compatible with the given <code>Comparator</code>.  The second type of constructor takes no <code>Comparator</code> argument, yet it, too, lets the client fill in any type for the type parameter.  This is broken, as it should allow only classes that implement <code>Comparable</code>.
          </p>

        </div>

        <xhtml:h5>The Solution</xhtml:h5>
        <div>

          <p>
          The fix is to remove <code>TreeSet</code>'s constructors in favor of static factory methods:
          </p>

<pre>&lt;E&gt; TreeSet&lt;E&gt; newTreeSet(Comparator&lt;? super E&gt; comparator);
&lt;E extends Comparable&lt;E&gt;&gt; TreeSet&lt;E&gt; newTreeSet();</pre>

          <p>
          As before, clients that provide a <code>Comparator</code> can create <code>TreeSet</code> instances for non‐<code>Comparable</code> types.  But now an attempt to create a <code>TreeSet</code> instance for a non‐<code>Comparable</code> type <em>without</em> supplying a <code>Comparator</code> will fail at compile time.
          </p>

          <p>
          Another option is to do away with the no‐arg constructor entirely and to force callers to pass <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Comparators.html#naturalOrder()"><code>Comparators.naturalOrder()</code></a>, a <code>Comparator&lt;C&gt;</code> for any <code>C</code> that extends <code>Comparable</code>, to the remaining constructor.  It won't take many calls to <code>new TreeSet&lt;T&gt;(Comparators.&lt;T&gt;naturalOrder())</code> to suggest that a static factory method is in order.
          </p>

          <p>
          Java trivia: Parameterized constructors are permitted:
          </p>

<pre>private &lt;T&gt; MyClass() { ... }</pre>

          <p>
          However, I have not found a way to use parameterized constructors to produce an equivalent solution.
          </p>

        </div>

        <xhtml:h5>Applications</xhtml:h5>
        <div>

          <p>
          <code>TreeSet</code> and other <code>SortedSet</code> implementations are the obvious example.  I could also imagine a scenario in which a class can serialize either (a) a class that knows how to convert itself to a string or (b) an arbitrary object plus an object that knows how to convert it to a string.  These cases are analogous the <code>SortedSet</code> case: <strong>Some objects can perform the necessary tasks themselves, while others require an external converter.</strong>  Static factory methods allow us to check uses of both types at compile time.
          </p>

<pre>&lt;E&gt; Serializer&lt;E&gt; newStringSerializer(Stringifier&lt;E&gt; stringifier);
&lt;E extends Stringifiable&gt; Serializer&lt;E&gt; newStringSerializer();</pre>

          <p>It's also possible to permit only a fixed set of type parameters:</p>

<pre>Serializer&lt;Integer&gt; newSerializer();
Serializer&lt;String&gt; newSerializer();</pre>

        </div>

      </div>

    </div>

  </div>
      </div>
    </content>
  </entry><entry>
    <updated>2008-08-12T21:20:00-05:00</updated>
    <summary>
            New: Static factory methods can do even more tricks.</summary>
    <title type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">Static Factory Methods</div>
    </title>
    <link rel="alternate" type="application/xhtml+xml" href="http://twofoos.org/content/static-factory-methods/#update_2008-08-12T21:20:00-05:00"/>
    <id>http://twofoos.org/content/static-factory-methods/#update_2008-08-12T21:20:00-05:00</id>
    <category term="effective-java"/>
    <category term="java"/>
    <content type="xhtml" xml:base="http://twofoos.org/">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <strong>initial posting</strong>
        <div>
  

    <xhtml:h3>Book Summary</xhtml:h3>
    <div>
      <p>Static factory methods can:</p>
      <ul>
        <li>have names</li>
        <li>control when new instances are created</li>
        <li>return any subtype of their return type</li>
        <li>reduce the need to specify type parameters</li>
      </ul>
    </div>

    <xhtml:h3>Additional Points</xhtml:h3>
    <div>

    <p>Static factory methods can assist in safe publication and can allow for selective type bounds.</p>

      <xhtml:h4>Safe Publication</xhtml:h4>
      <div>

        <p>Sometimes you want to create an object and publish a reference to it at the same time.  Sometimes you publish the reference where other threads can see it.  The obvious approach is to handle it all in the constructor:</p>
<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;

  public Request(Query query, User user) {
    this.query = query;
    this.user = user;

    sampleRequest = this;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Notice that <code>sampleRequest</code> is not declared <code>volatile</code>.  The intent is to give up the guarantee that all threads will see the most recent value in favor of the speed of a non‐volatile write.  And it would work if only the code were slightly different:</p>

<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;
<ins style="display: inline; font-weight: bold;">
  public static Request create(Query query, User user) {
    Request request = new Request(query, user);
    sampleRequest = request;
    return request;
  }

  private</ins> Request(Query query, User user) {
    this.query = query;
    this.user = user;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Readers of an object published by the former code can behave nondeterministically.  But the latter code, by waiting until after the constructor to publish the reference (and by containing no non‐final fields), takes advantage of a feature of the memory model: the end‐of‐constructor "freeze."  This freeze ensures that the object appears fully initialized (and thus immutable) to other threads.  <a href="http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html">Read Jeremy Manson's article on immutability</a>, and see also <a href="http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1218588162&amp;sr=8-1">Java Concurrency in Practice</a> pg. 41–42.</p>

        <p>What does this esoteric knowledge gain you?  Very little.  The reason is that examples like the above are rare.  In most cases, the act of publishing the reference is a <code>volatile</code> write or another synchronization action, such as adding the reference to a thread‐safe list of listeners.  Such actions guarantee that all steps performed before the publishing step are visible to all threads reading the reference.  The end‐of‐constructor freeze is superfluous.</p>

        <p>All this said, if you depend on others to write defensive code and they depend on you, you'll have problems.  Incomplete object initialization can be a security vulnerability:  An uninitialized "immutable" object might appear to contain an innocuous request during security checks, only to transform into a malicious one before execution.  <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370">Maybe spawning 0 processes is acceptable but 1,000,000 is not, or maybe 0 is a valid seed in a crypto algorithm but 1,000,000 is not.</a></p>

      </div>

      <xhtml:h4>Selective Type Bounds</xhtml:h4>
      <div>

        <xhtml:h5>The Problem</xhtml:h5>
        <div>

          <p>
          When parameterizing a class, I can choose to set bounds on the type parameter.  For example, <code>EnumSet</code> has type parameter <code>&lt;E extends Enum&lt;E&gt;&gt;</code>.  Or I can leave it unbounded: <code>HashSet</code> has type parameter <code>E</code>.
          </p>
          
          <p>
          Bounded or unbounded: What other options do I need?  Consider <code>TreeSet</code>.  <code>TreeSet</code> instances divide into two groups: those with a <code>Comparator</code> and those without.  When the caller provides a <code>Comparator</code>, the <code>TreeSet</code> can contain any kind of element supported by the <code>Comparator</code>.  Since I can define a <code>Comparator</code> for any type that I like, I can create a <code>TreeSet&lt;List&gt;</code>, a <code>TreeSet&lt;Rectangle&gt;</code>, or any other type, so long as I provide an appropriate <code>Comparator</code>.  On the other hand, when the caller does not provide a <code>Comparator</code>, the <code>TreeSet</code> can only contain elements that implement <code>Comparable</code> (specifically, elements that are <code>Comparable</code> to one another).  A <code>TreeSet&lt;List&gt;</code> without a <code>Comparator</code> will throw exceptions when it is used.
          </p>

          <p>
          The class's type parameter alone cannot provide us with the flexibility to solve this problem.  The result is two kinds of <code>TreeSet</code> constructors.  The first takes a <code>Comparator</code>.  As it should, it allows the caller to fill in any type for the type parameter, provided that it's compatible with the given <code>Comparator</code>.  The second type of constructor takes no <code>Comparator</code> argument, yet it, too, lets the client fill in any type for the type parameter.  This is broken, as it should allow only classes that implement <code>Comparable</code>.
          </p>

        </div>

        <xhtml:h5>The Solution</xhtml:h5>
        <div>

          <p>
          The fix is to remove <code>TreeSet</code>'s constructors in favor of static factory methods:
          </p>

<pre>&lt;E&gt; TreeSet&lt;E&gt; newTreeSet(Comparator&lt;? super E&gt; comparator);
&lt;E extends Comparable&lt;E&gt;&gt; TreeSet&lt;E&gt; newTreeSet();</pre>

          <p>
          As before, clients that provide a <code>Comparator</code> can create <code>TreeSet</code> instances for non‐<code>Comparable</code> types.  But now an attempt to create a <code>TreeSet</code> instance for a non‐<code>Comparable</code> type <em>without</em> supplying a <code>Comparator</code> will fail at compile time.
          </p>

          <p>
          Another option is to do away with the no‐arg constructor entirely and to force callers to pass <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Comparators.html#naturalOrder()"><code>Comparators.naturalOrder()</code></a>, a <code>Comparator&lt;C&gt;</code> for any <code>C</code> that extends <code>Comparable</code>, to the remaining constructor.  It won't take many calls to <code>new TreeSet&lt;T&gt;(Comparators.&lt;T&gt;naturalOrder())</code> to suggest that a static factory method is in order.
          </p>

          <p>
          Java trivia: Parameterized constructors are permitted:
          </p>

<pre>private &lt;T&gt; MyClass() { ... }</pre>

          <p>
          However, I have not found a way to use parameterized constructors to produce an equivalent solution.
          </p>

        </div>

        <xhtml:h5>Applications</xhtml:h5>
        <div>

          <p>
          <code>TreeSet</code> and other <code>SortedSet</code> implementations are the obvious example.  I could also imagine a scenario in which a class can serialize either (a) a class that knows how to convert itself to a string or (b) an arbitrary object plus an object that knows how to convert it to a string.  These cases are analogous the <code>SortedSet</code> case: <strong>Some objects can perform the necessary tasks themselves, while others require an external converter.</strong>  Static factory methods allow us to check uses of both types at compile time.
          </p>

<pre>&lt;E&gt; Serializer&lt;E&gt; newStringSerializer(Stringifier&lt;E&gt; stringifier);
&lt;E extends Stringifiable&gt; Serializer&lt;E&gt; newStringSerializer();</pre>

          <p>It's also possible to permit only a fixed set of type parameters:</p>

<pre>Serializer&lt;Integer&gt; newSerializer();
Serializer&lt;String&gt; newSerializer();</pre>

        </div>

      </div>

    </div>

  
  </div>
      </div>
    </content>
  </entry></feed>
