Search code examples
javaintcomparatordereference

java comparing integers as strings with a comparator - odd results


I'm attemping to compare some players with a comparator by the amount of runs they have obtained.

System.out.println("Comparing: " + p2.getRuns() + " and " + p1.getRuns());
int newRESULT = intConvert(p2.getRuns()).compareTo(intConvert(p1.getRuns()));
System.out.println("Returns: " + newRESULT);
return newRESULT;

However this returns:

Comparing: 25 and 0, Returns: 2

Comparing: 0 and 100, Returns: -1

Comparing: 25 and 100, Returns: 1

...and hence orders the players in the wrong order.

Should the first comparison not return 1, the second -1 and the last -1 as well?

intConvert:

     private static String intConvert(int x)
     {
      return "" + x;
     }

Solution

  • I assume intConvert(...) converts an int to a String, and thus you get lexical comparisons which meahs "25" is greater than "100" because the first character is greater (2 > 1).

    If you want to get correct comparisons stick to comparing ints or if you need to use a String create strings of equal length and fill in missings zeros at the front (e.g. 25 -> "025").