title: Java Collections sort: Comparison method violates its general contract
body: <p>I know it has been asked and answered millions of times but still I am unable to figure out why I am receiving with the violation during sort. Here is my code:</p>
  
  <pre><code>Collections.sort(sorted, new Comparator&lt;MyObject&gt;() {
      @Override
      public int compare(MyObject m1, MyObject m2) {
          // Actual energy comparison :-
          // THE higher the energy, the earlier in the list
          float delta = m1.getTotalEnergy() - m2.getTotalEnergy();
  
          if (delta &gt; 0) {
              return 1;
          } else if (delta &lt; 0) {
              return -1;
          } else {
              return 0;
          }
      }
  });
  </code></pre>
  
  <p>and I receive this error</p>
  
  <pre class="lang-none prettyprint-override"><code>java.lang.IllegalArgumentException: Comparison method violates its general contract!  
          at java.util.TimSort.mergeHi(TimSort.java:895)  
          at java.util.TimSort.mergeAt(TimSort.java:512)  
          at java.util.TimSort.mergeForceCollapse(TimSort.java:453)  
          at java.util.TimSort.sort(TimSort.java:250)  
          at java.util.Arrays.sort(Arrays.java:1512)  
          at java.util.ArrayList.sort(ArrayList.java:1454)  
          at java.util.Collections.sort(Collections.java:175)
  </code></pre>
  
  <p>Any ideas ? </p>