无法找到属于对象的方法 [英] Unable to find a method belonging to an object

查看:143
本文介绍了无法找到属于对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I believe I am making a really simple mistake/ overlooking something trivial.

import java.util.Comparator;

public class NaturalComparator<Integer> {

    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

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

Why am I unable to access the intValue() method in the Integer class?

推荐答案

你是 shadowing 类型 java.lang .Integer 带有一个类型参数变量你决定命名整数

You are shadowing the type java.lang.Integer with a type parameter variable you decided to name Integer.

你的代码相当于

public class NaturalComparator<T> {

    public int compare(T o1, T o2) {
        return o1.intValue() - o2.intValue();
    }
}

自<$ c $以来,显然无法编译c> Object ( T 的界限)未声明 intValue()方法。

Which obviously doesn't compile since Object (the bound of T) doesn't declare a intValue() method.

你想要的是

public class NaturalComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.intValue() - o2.intValue();
    }
}

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

in which case java.lang.Integer is used as a type argument.

这篇关于无法找到属于对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆