title: Why does this program using Collections.sort only fail for lists of size 32 or more?
body: <p>The following program throws the following exception:</p>
  
  <pre><code>java.lang.IllegalArgumentException: Comparison method violates its general contract!
  </code></pre>
  
  <p>I understand the problem with the <code>Comparator</code>. See <a href="https://stackoverflow.com/questions/29865439/unable-to-replicate-comparison-method-violates-its-general-contract">Unable to replicate : &quot;Comparison method violates its general contract!&quot;</a></p>
  
  <p>I don't understand why it only fails for <code>List</code>s of size 32 or more. Can anyone explain?</p>
  
  <pre><code>class Experiment {
  
      private static final class MyInteger {
          private final Integer num;
  
          MyInteger(Integer num) {
              this.num = num;
          }
      }
  
      private static final Comparator&lt;MyInteger&gt; COMPARATOR = (r1, r2) -&gt; {
          if (r1.num == null || r2.num == null)
              return 0;
          return Integer.compare(r1.num, r2.num);
      };
  
      public static void main(String[] args) {
          MyInteger[] array = {new MyInteger(0), new MyInteger(1), new MyInteger(null)};
          Random random = new Random();
          for (int length = 0;; length++) {
              for (int attempt = 0; attempt &lt; 100000; attempt++) {
                  List&lt;MyInteger&gt; list = new ArrayList&lt;&gt;();
                  int[] arr = new int[length];
                  for (int k = 0; k &lt; length; k++) {
                      int rand = random.nextInt(3);
                      arr[k] = rand;
                      list.add(array[rand]);
                  }
                  try {
                      Collections.sort(list, COMPARATOR);
                  } catch (Exception e) {
                      System.out.println(arr.length + " " + Arrays.toString(arr));
                      return;
                  }
              }
          }
      }
  }
  </code></pre>