Java:“?扩展我无法转换为“?"扩展我 [英] Java: "? extends I" cannot be converted to "? extends I"

查看:126
本文介绍了Java:“?扩展我无法转换为“?"扩展我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

interface I {}

public class Test {

    TableView<? extends I> table;

    Test(ObservableList<? extends I> list) {
        table = new TableView<>();
        table.setItems(list);
    }
}

...产生此消息:

error: method setItems in class TableView<S> cannot be applied to given types;
       table.setItems(list);
 required: ObservableList<CAP#1>
 found: ObservableList<CAP#2>
 reason: argument mismatch; ObservableList<CAP#2> cannot be converted to ObservableList<CAP#1>
 where S is a type-variable:
   S extends Object declared in class TableView
 where CAP#1,CAP#2 are fresh type-variables:
   CAP#1 extends I from capture of ? extends I
   CAP#2 extends I from capture of ? extends I

两个相同类型之间如何存在类型不匹配?我想念什么?

How can there be a type mismatch between two identical types? What am I missing?

推荐答案

在Java泛型中,?通配符不能相同,因为它们代表未知类型.未知类型不能等于某些其他未知类型.

In Java Generics, ? wildcards cannot be identical, because they represent unknown types. An unknown type cannot equal some other unknown type.

如果希望类型匹配,则必须在Test类上定义一个泛型类型参数,并在整个类中对其进行引用.

If you want the types to match, then you must define a generic type parameter on the Test class, and refer to it throughout your class.

public class Test<T extends I> {

    TableView<T> table;

    Test(ObservableList<T> list) {
        table = new TableView<>();
        table.setItems(list);
    }
}

这篇关于Java:“?扩展我无法转换为“?"扩展我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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