Java override compareTo, Long

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

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

Code example:

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 long, long

+4
source share
6 answers

, MyEntry<K, V> , . , . - , ( , Comparable),

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

- , :

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;
}
+8
Long l1 = new Long(3);
Long l2 = new Long(2);

return l1.compareTo(l2);

?

+8

:

@Override
public int compareTo(MyEntry<K, V> object) {
        if (object == null) {
            throw new NullPointerException("Null parameter");
        } else if (!this.getClass().equals(object.getClass())) {
            throw new ClassCastException("Possible ClassLoader issue.");
        } else {
            return this.longValue.compareTo(object.longValue);
        }

}

, Java. , .

+2

, compareTo Long.

Java , compareTo.

Java.

@Override
                public int compare(long t1, long t2) {
                    return Long.valueOf(t1).compareTo(t2);
                }
+1

longValue() .

: -

Long id1 = obj.getId();
Long id2 = obj1.getId();

if (id1.longValue() <= id2.longValue()) {
Sysout.......
}

assertTrue(id1.longValue() == id2.longValue())
0

The long compareTo command may help. The compareTo method returns an integer value to give you an answer as to whether the long ones are equal, more or less than each other.

Long l1 = new Long(63255);
 Long l2 = new Long(71678);
 int returnVal =  l1.compareTo(l2);

 if(returnVal > 0) {
    System.out.println("l1 is greater than l2");
 }
 else if(returnVal < 0) {
    System.out.println("l1 is less than l2");
 }
 else {
    System.out.println("l1 is equal to l2");
 }
-1
source

All Articles