Why is my simple comparator broken?

前端 未结 6 1250
故里飘歌
故里飘歌 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:07

    Integer overflow… or more precisely, underflow.

    Instead, do an explicit comparison:

    private static final Comparator reverse = new Comparator() {
        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.

提交回复
热议问题