title: Java: TreeSet compareTo method triggered at first add call
body: <p>The following java code utilizes a <code>TreeSet</code> to collect objects derived from the class <code>MyClass</code> which doesn't implement the <code>Comparable</code> interface nor have a <code>compareTo()</code> method to perform the comparison between objects. By not providing that comparison method, we expect the raising of an exception during the addition of the <strong>second</strong> object, not the <strong>first</strong> one as soon as comparison is ambiguous with only one object. </p>
  
  <p>JDK: 1.7</p>
  
  <p>Question:
  Why the <code>compareTo()</code> is triggered on the <strong>first</strong> add <code>tree.add(m1)</code> ?</p>
  
  <p>Code:</p>
  
  <pre><code>package javaapplication1;
  
  import java.util.*;
  
  class MyClass
  {
      int _x;
      MyClass(int x)
      {
          _x = x;
      }
  }
  
  public class JavaApplication1 
  {
       public static void main(String[] args) 
       {
           MyClass m1 = new MyClass(5);
           MyClass m2 = new MyClass(3);
  
           TreeSet tree = new TreeSet();
           tree.add(m1);
           tree.add(m2);
       }
  }
  </code></pre>