Pair Class


posted on Nov. 21, 2019, 4:07 p.m.
public class Main {
    static class Pair implements Comparable<Pair>{
        // fields
        int x;
        int y;
        // constructor
        Pair (int a, int b){
            x = a;
            y = b;
        }

        // Arrays.sort() calls compareTo, we are telling Java how to sort Pair
        public int compareTo(Pair o) {
            return x-o.x;
        }
    }

    public static void main(String[] args) {
        Pair p1 = new Pair(5, 4);
        Pair arr[] = new Pair[5];
        // assume i input it already
        Arrays.sort(arr);
    }
}

Comments


  • 3
    wleungBVG  commented on March 8, 2020, 10:34 p.m.

    Using subtraction in the compareTo function is dangerous as it can result in integer overflow/underflow. It is best to determine whether to return -1, 0, or -1 using if statements rather than subtraction.


    • 0
      Encodeous  commented on March 12, 2020, 7:42 a.m.

      Or in this case, you can use Integer.compare for the x values.


    • 2
      sankeeth_ganeswaran  commented on March 9, 2020, 6:07 p.m.

      thanks dude