Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator return type is not compatible with integer

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 ??

like image 576
Computernerd Avatar asked Jan 08 '23 09:01

Computernerd


2 Answers

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);     
}
like image 96
Jean Logeart Avatar answered Jan 11 '23 00:01

Jean Logeart


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; 
    }
});
like image 35
Everv0id Avatar answered Jan 10 '23 22:01

Everv0id