Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java override compareTo, Long

I have a class that implements the Comparable interface. In this class I need to override compareTo method in order to sort objects by Long values.

What I don't know is how to perform is the comparison of the Long type. I get error when trying to check if value is greater than or less than another Long value. I know Long is the object of long, but have no idea how to compare two Long's.

Code sample:

public int compareTo(MyEntry<K, V> object) {
    if (this.value < object.value)
        return -1;
    if (this.value.equals(object.value))
        return 0;

    return 1;
}

Error message:

           operator < cannot be applied to V,V
if (this.value < object.value)
                       ^

V, V is Long, Long

like image 440
user1121487 Avatar asked Oct 10 '13 16:10

user1121487


People also ask

Can we override compareTo method in Java?

In order to change the sorting of the objects according to the need of operation first, we have to implement a Comparable interface in the class and override the compareTo() method.

Do you have to override compareTo?

So essentially you need to override compareTo() because you need to sort elements in ArrayList or any other Collection.

Will two object always be equal when their compareTo () method returns zero?

Now, if Comparable returns Zero, it means two objects are the same by comparison. If two objects are the same by using the equals method, it returns true.


1 Answers

Your problem is that MyEntry<K, V> doesn't tell the compiler what type of Object you're trying to compare. It doesn't know that you're comparing Long values. The best way to do this is to not worry about what type of Object you're comparing (assuming your object implements Comparable) by just using

return this.value.compareTo(object.value);

but if you want to do it manually for some reason, do this:

public int compareTo(MyEntry<K, V> object) {
    if ((Long) this.value < (Long) object.value)
        return -1;
    if (this.value.equals(object.value))
        return 0;

    return 1;
}
like image 52
StormeHawke Avatar answered Sep 30 '22 03:09

StormeHawke