Why is my simple comparator broken?

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

提交回复
热议问题