使用compare方法的可比接口

use*_*650 2 java comparable

任何人都可以解释为什么下面的代码不起作用:

public static void main(String[] args) throws IOException
 {
    Comparable<Integer> q = new Integer(4);
    Comparable<Integer> o = new Integer(4);
    // Problematic line
    int j = o.compareTo(q);

    if (j == -1)
        System.out.println("yes");
    else
        System.out.println("no");
 }
Run Code Online (Sandbox Code Playgroud)

但是这个有效:

public static void main(String[] args) throws IOException
 {
    Integer q = new Integer(4);
    Integer o = new Integer(4);

            // Problematic line
    int j = o.compareTo(q);

    if (j == -1)
        System.out.println("yes");
    else
        System.out.println("no");
 }

  }
Run Code Online (Sandbox Code Playgroud)


换句话说,什么时候接口实现是可以互换的,而不是创建普通的类实例?当我使用compareTo()方法时出现错误,该方法是Comparable接口的一部分,并由所有Wrapper类(如Integers)实现.

所以我猜Comparable<Integer> q = new Integer(4);,Integer q = new Integer(4);不应该有任何区别.有人可以解释一下吗?

谢谢.

Sot*_*lis 5

Comparable#compareTo()方法的参数是类型T,其中T是类型的泛型类型变量Comparable.换句话说,对于声明为的变量Comparable<Integer>,该方法只接受一个Integer.您尝试传递的参数声明为Comparable<Integer>不兼容的类型.