无法找到属于对象的方法
我相信我犯了一个非常简单的错误/忽略了一些微不足道的事情。
import java.util.Comparator; public class NaturalComparator { public int compare(Integer o1, Integer o2) { return o1.intValue() - o2.intValue(); } }
编译时收到以下错误。
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
为什么我无法访问Integer类中的intValue()方法?
您正在使用类型参数变量为java.lang.Integer
类型设置阴影 ,您决定将其命名为Integer
。
你的代码相当于
public class NaturalComparator { public int compare(T o1, T o2) { return o1.intValue() - o2.intValue(); } }
由于Object
( T
的边界)未声明intValue()
方法,因此显然无法编译。
你想要的是什么
public class NaturalComparator implements Comparator { @Override public int compare(Integer o1, Integer o2) { return o1.intValue() - o2.intValue(); } }
在这种情况下, java.lang.Integer
用作类型参数。
您不小心创建了一个generics类型参数Integer
,该参数与Integer
类无关,并且您没有实现Comparator
。 尝试
public class NaturalComparator implements Comparator
在类声明中的<>
放置标识符声明了generics类型参数,但在implements / extends子句中的<>
放置标识符是传递类型参数。