且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java泛型不兼容类型(不存在类型变量T的实例)

更新时间:2023-10-11 11:56:52

最小化您的示例(使用模板化List类型的Integer):

Minimize your example like (using Integer of the templated List type):

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<Integer> list = new ArrayList<Integer>();
        ArrayList<Integer> inRange = Helper.inRange(list, 0,1);
    }
}

class Helper {
    public static <T> List<T> inRange(List<T> list, int index, int range) {
        List<T> res = new ArrayList<T>();
        return res;
    }
}

然后,即使您将模板类型放在图片之外:

Then even if you put template types out of the picture:

ArrayList inRange = Helper.inRange(list, 0,1);

public static List inRange(List list, int index, int range) { ... }

您看到,当辅助静态方法返回List时,您正在尝试将其分配给ArrayList,这就是您的问题,因为ArrayList是List的具体实现,但是您不能将对通用List的引用分配给ArrayList的具体实现

you see that while the helper static method returns a List, you are trying to assign it to an ArrayList, and that's your problem, as ArrayList is a concrete implementation of List, but you cannot assign a reference to a generic List to a concrete implementation of ArrayList

只需更改为:

List<View> inRange = Helper.inRange(gameView.activePlayersViews(), pos, 
        playerView.range());

您很高兴: https://ideone.com/MXZxqz