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
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.Or in this case, you can use
Integer.compare
for the x values.thanks dude