Why is my simple comparator broken?

前端 未结 6 1249
故里飘歌
故里飘歌 2021-01-04 01:56

I have a class, which I have simplified to this:

final class Thing {
    private final int value;
    public Thing(int value) {
        this.value = value;
          


        
相关标签:
6条回答
  • 2021-01-04 02:01

    try

    System.out.println(Integer.MAX_Value - Integer.MIN_VALUE);
    

    This needs to return a positive number as MAX_VALUE > MIN_VALUE but instead prints -1

    0 讨论(0)
  • 2021-01-04 02:07

    Integer overflow… or more precisely, underflow.

    Instead, do an explicit comparison:

    private static final Comparator<Thing> reverse = new Comparator<Thing>() {
        public int compare(Thing a, Thing b) {
          int av = a.getValue(), bv = b.getValue();
          return (av == bv) ? 0 : ((av < bv) ? -1 : +1);
        }
    };
    

    Using subtraction is fine if you are sure that the difference won't "wrap around". For example, when the values in question are constrained to be non-negative.

    0 讨论(0)
  • 2021-01-04 02:08

    What kind of numbers do you throw in there? If your numbers are large enough, you could wrap through the MIN/MAX values for integers and end up in a mess.

    0 讨论(0)
  • 2021-01-04 02:11

    You cannot use minus to create the comparison. You'll overflow when the absolute difference exceeds Integer.MAX_VALUE.

    Instead, use this algorithm:

    int compareInts( int x, int y ) {
      if ( x < y ) return -1;
      if ( x > y ) return 1;
      return 0;
    }
    

    I like to have this function in a library for such purposes.

    0 讨论(0)
  • 2021-01-04 02:14

    When comparing Java primitives, it is advisable to convert them to their Object counterparts and rely on their compareTo() methods.

    In this case you can do:

    return Integer.valueOf(a.getValue()).compareTo(b.getValue())
    

    When in doubt, use a well-tested library.

    0 讨论(0)
  • 2021-01-04 02:22

    If a's value is very negative and b's value is very positive your answer will be very wrong.

    IIRC, Int overflow silently wraps around in the JVM

    -- MarkusQ

    0 讨论(0)
提交回复
热议问题