Reputation:
i have one class which have 4 int fields . i want to sort objects array by some mathematical operation on fields .I tried below code but sorting is not happening.
class Cust1 implements Comparable<Cust1>{
int a;
int o;
int s;
int p;
@Override
public int compareTo(Cust1 b) {
if(this.a + this.s <= b.a + b.s)
{
return 1;
}
else {
return 0;
}
}
}
public class Test5 {
public static void main (String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Cust1[] cust = new Cust1[n];
for(int i=0;i<n ;i++)
{
Cust1 a = new Cust1();
String[] str = br.readLine().split(" ");
a.a = Integer.parseInt(str[0]);
a.o = Integer.parseInt(str[1]);
a.s = Integer.parseInt(str[2]);
a.p = Integer.parseInt(str[3]);
cust[i] =a;
}
Arrays.sort(cust, new Comparator<Cust1>() {
@Override
public int compare(Cust1 o1, Cust1 o2) {
return o1.compareTo(o2);
}
});
}
}
Upvotes: 1
Views: 76
Reputation: 18245
You comparator work wrong. It should return:
<0 - current object is less than another one
class Cust1 implements Comparable {
int a;
int o;
int s;
int p;
@Override
public int compareTo(Cust1 b) {
return Integer.compare(a + s, b.a + b.s);
}
}
And you do not have to provide additional comparator to Arrays.sort()
since Cust1
already implements Comparable
.
Upvotes: 0
Reputation: 4365
Based on your code snippet: you don't need to provide Comparator
, since Cust1
already implements Comparable
. So, this should be enough:
Arrays.sort(cust);
Also, Cust1
implementation of Comparable
doesn't really tell, when one object is less then
other. Probably, you meant something like this:
@Override
public int compareTo(Cust1 b) {
if(this.a + this.s < b.a + b.s) {
return 1;
} else if (this.a + this.s > b.a + b.s) {
return -1;
} else {
return 0;
}
}
But it's hard to tell, what exact implementation of Comparable
should be without more details (for instance, for some reason fields o
and p
are not involved in comparison at all).
Upvotes: 1