title: Java Comparator Sort Differently
body: <p>public class StringComparatorTest {</p>
  
  <pre><code>public static void main(String[] args) {
      String[] a = {"abc9", "abc", "abc123", "ab9"};
      String[] b = {"abc9", "abc", "abc123", "ab9"};
      String[] c = {"abc9", "abc", "abc123", "ab9"};
  
      System.out.print("a_Origin     : ");
      printArray(a);
      System.out.print("c_Origin     : ");
      printArray(c);
  
      System.out.print("a_Default    : ");
      Arrays.sort(a);
      printArray(a);
  
      System.out.print("c_Default    : ");
      Arrays.sort(c);
      printArray(c);
  
      System.out.print("a_Customized1: ");
      Arrays.sort(a, new StringComparator());
      printArray(a);
  
      System.out.print("b_Customized1: ");
      Arrays.sort(b, new StringComparator());
      printArray(b);
  
      System.out.print("c_Customized2: ");
      Arrays.sort(c, new StringComparator2());
      printArray(c);
  }
  
  public static void printArray(String[] arr){
      for (String str: arr) {
          System.out.print(str + " ");
      }
      System.out.println();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>public class StringComparator implements Comparator {</p>
  
  <pre><code>@Override
  public int compare(String s1, String s2) {
      if(s1.length() == s2.length()){
          if(s1.equals(s2))
              return 0;
          else{
              for(int i = 0; i &lt; s1.length(); i++){
                  if(s1.charAt(i) &gt; s2.charAt(i)){
                      return 1;
                  }else {
                      return -1;
                  }
              }
              return 0;
          }
      }else if(s1.length() &lt; s2.length()){
          return -1;
      }else{
          return 1;
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>public class StringComparator2 implements Comparator {</p>
  
  <pre><code>@Override
  public int compare(String s1, String s2) {
      if (s1.length() == s2.length()) {
          for (int i = 0; i &lt; s1.length(); i++) {
              if (s1.charAt(i) &gt; s2.charAt(i)) {
                  return 1;
              } else if (s1.charAt(i) &lt; s2.charAt(i)) {
                  return -1;
              }
          }
          return 0;
      } else if (s1.length() &lt; s2.length()) {
          return -1;
      } else {
          return 1;
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I have to comparators to sort a String objects, it turns out the "StringComparator" has some bugs but I can't figure out. </p>
  
  <p>"StringComparator" works fine at 
  "Arrays.sort(b, new StringComparator());"
  the out put order is as expected.</p>
  
  <p>but when I use Default sort(steps below) and then sort by "StringComparator", the bug shows:</p>
  
  <p>" Arrays.sort(a);
   Arrays.sort(a, new StringComparator());"</p>
  
  <p>the out put orders are different which should be the same.
  (Array a and b are same)</p>
  
  <p>Can someone explain a little bit? 
  Thanks a lot~</p>