Java覆盖compareTo,Long

use*_*487 4 java compareto comparable

我有一个实现Comparable接口的类.在这个类中,我需要覆盖compareTo方法,以便按Long值对对象进行排序.

我不知道的是如何执行是Long类型的比较.尝试检查值是否大于或小于另一个Long值时出错.我知道龙是长期的对象,但不知道如何比较两个龙的.

代码示例:

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

    return 1;
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

           operator < cannot be applied to V,V
if (this.value < object.value)
                       ^
Run Code Online (Sandbox Code Playgroud)

V,V长,长

Sto*_*wke 9

你的问题是MyEntry<K, V>没有告诉编译器你想要比较什么类型的Object.它不知道您正在比较Long值.执行此操作的最佳方法是不要担心您要比较的对象类型(假设您的对象实现了Comparable),只需使用

return this.value.compareTo(object.value);
Run Code Online (Sandbox Code Playgroud)

但如果您想出于某种原因手动执行此操作,请执行以下操作:

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;
}
Run Code Online (Sandbox Code Playgroud)


Ade*_*ros 8

Long l1 = new Long(3);
Long l2 = new Long(2);

return l1.compareTo(l2);
Run Code Online (Sandbox Code Playgroud)

简单没有?