I am trying to sort an object via the object attribute NodeID which is long type.
Collections.sort(PeerNodeInChord, new Comparator<PeerNode>()
{
@Override public long compare(PeerNode p1, PeerNode p2)
{
return p1.NodeID - p2.NodeID; // Ascending
}
});
I am getting the following error :
compare(PeerNode,PeerNode) in cannot implement compare(T,T) in Comparator return type long is not compatible with int where T is a type-variable: T extends Object declared in interface Comparator
It seems i cant have type "long" as return type and must have "int" as the return type.
I am not allowed to change NodeID type to int.
Is there any way to sort the ArrayList of PeerNode via the object attribute NodeID which is long type ??
Don't reinvent the wheel and simply delegate to the compare
method from Long
:
@Override
public int compare(PeerNode p1, PeerNode p2) {
return Long.compare(p1.NodeID, p2.NodeID);
}
Out of curiosity, you can give a look to the Long.compare
implementation which is:
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Collections.sort(PeerNodeInChord, new Comparator<PeerNode>() {
@Override
public int compare(PeerNode p1, PeerNode p2) {
long dif = p1.NodeID - p2.NodeID;
if (dif > 0) return 1;
if (dif < 0) return -1;
return 0;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With