title: Java: Problems with TreeSet
body: <p>I have a class Odp. I want to use TreeSet to keep a sorted collection of Odp objects. However, I've been having problems.</p>
  
  <pre><code>public class OdpStorage {
  
      private TreeSet&lt;Odp&gt; collection = new TreeSet&lt;Odp&gt;(); 
  
      public addOdp(Odp o) {
            return collection.add(o);
      }
  
      public int size() {
            return collection.size();
      }
  
  }
  </code></pre>
  
  <p>collection.add(Odp o) is supposed to do nothing if it's already in the tree, right? Somehow, this unit test fails: </p>
  
  <pre><code>OdpStorage ts = new OdpStorage();       
  Odp ftw = new Odp("LOL");
      Odp ktr = new Odp("OMG");
  
      ts.addOdp(ftw);
  
      ts.addOdp(ftw); //should do nothing
      ts.addOdp(ftw); //should do nothing
      ts.addOdp(ftw); //should do nothing
      ts.addOdp(ktr);
  
  assertEquals(2, ts.size());
  </code></pre>
  
  <p>The assertion fails. It expects 2, but the return value is 5. Why? Could the odp.equals() function be messed up? </p>
  
  <p>Similarly, calling <code>collection.contains(o)</code> fails, even when the there is an object in the set <code>X</code> for which <code>o.equals(X)</code> returns true.</p>
  
  <p>The .equals() function of Odp: (generated by Eclipse)</p>
  
  <pre><code>public boolean equals(Object obj) {
      if (this == obj)
          return true;
      if (obj == null)
          return false;
      if (!(obj instanceof Odp))
          return false;
      Gene other = (Odp) obj;
      if (sequence == null) {
          if (other.sequence != null)
              return false;
      } else if (!sequence.equals(other.sequence))
          return false;
      return true;
  }
  </code></pre>
  
  <p>compareTo:</p>
  
  <pre><code>/**
   * this = g0
   * if they are equal, g1 is presumed to come first
   * 
   *  @return -1 if g0 comes before g1; 1 if g0 comes after g1
   */
  @Override
  public int compareTo(Odp g1) {
  
      if (sequence.length() &lt; g1.getSeq().length()) {
          return -1;
      }
      else if (sequence.length() &gt; g1.getSeq().length()) {
          return 1;
      }
  
      if (sequence.compareTo(g1.getSeq()) &lt; 0) {
          return -1;
      }
  
      return 1;
  }
  </code></pre>
  
  <p><code>hashCode()</code> is not overridden. Problem?</p>
  
  <p><strong>UPDATE</strong>
  <code>hashCode()</code> is as follows:</p>
  
  <pre><code>@Override
  public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result
              + ((sequence == null) ? 0 : sequence.hashCode());
      return result;
  }
  </code></pre>
  
  <p>But that still doesn't solve the problem.</p>