title: Binary search in list with generic elements
body: <p>I have a list with custom elements and need to do a binary search through that list. However, I am getting weird results. I guess that the problem is in the compareTo method, but I don't know what I'm missing.</p>
  
  <pre><code>public static void main(String[] args) {
      List&lt;MyObject&gt; lista = new ArrayList&lt;&gt;();
  
      lista.add(new MyObject("MyObject 1"));
      lista.add(new MyObject("MyObject 2"));
      lista.add(new MyObject("MyObject 8"));
      lista.add(new MyObject("MyObject 3"));
      lista.add(new MyObject("MyObject 4"));
  
      int i = Collections.&lt;MyObject&gt;binarySearch(lista, new MyObject("MyObject 2"));
      System.out.println(i); //gives weird result if I search for the first two elements "MyObject 1" or "MyObject 2"
  }
  
  
  public class MyObject implements Comparable&lt;MyObject&gt; {
  
  private String sadrzaj;
  
  public MyObject(String s) {
      this.sadrzaj = s;
  }
  
  //empty constructor, getter, setter...
  
  @Override
  public String toString() {
      return this.sadrzaj;
  }   
  
  @Override
  public int compareTo(MyObject o) {
      if(o.toString().equals(this.toString())) {
          return 0;
      }
      return -1;
  }
  }
  </code></pre>