无法找到属于对象的方法

gra*_*ton 2 java

我相信我犯了一个非常简单的错误/忽略了一些微不足道的事情.

import java.util.Comparator;

public class NaturalComparator<Integer> {

    public int compare(Integer o1, Integer o2) {
        return o1.intValue() - o2.intValue();
    }
}
Run Code Online (Sandbox Code Playgroud)

编译时收到以下错误.

NaturalComparator.java:6: error: cannot find symbol
        return o1.intValue() - o2.intValue();
                 ^
  symbol:   method intValue()
  location: variable o1 of type Integer
  where Integer is a type-variable:
    Integer extends Object declared in class NaturalComparator
NaturalComparator.java:6: error: cannot find symbol
        return o1.intValue() - o2.intValue();
                                 ^
  symbol:   method intValue()
  location: variable o2 of type Integer
  where Integer is a type-variable:
    Integer extends Object declared in class NaturalComparator
2 errors
Run Code Online (Sandbox Code Playgroud)

为什么我无法访问Integer类中的intValue()方法?

Sot*_*lis 8

您正在使用您决定命名的类型参数变量来遮蔽类型.java.lang.IntegerInteger

你的代码相当于

public class NaturalComparator<T> {

    public int compare(T o1, T o2) {
        return o1.intValue() - o2.intValue();
    }
}
Run Code Online (Sandbox Code Playgroud)

显然不编译,因为Object(绑定T)不声明intValue()方法.

你想要的是什么

public class NaturalComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.intValue() - o2.intValue();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下java.lang.Integer用作类型参数.