Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java泛型:";嵌套的;类型参数?_Java_Generics_Polymorphism_Type Parameter - Fatal编程技术网

Java泛型:";嵌套的;类型参数?

Java泛型:";嵌套的;类型参数?,java,generics,polymorphism,type-parameter,Java,Generics,Polymorphism,Type Parameter,编辑:是,这可能是重复的。但是,另一个问题类似于“什么是电锯,我该如何使用它?”我的问题更像是“我正试图用这台机器在这里钻孔,但它不起作用-怎么了?”。当然,答案是“不要使用电锯!”一旦你知道你正在使用电锯,就很容易找到 但我甚至不知道我的问题与“原始类型vs.通配符”有关,因此没有发现这个问题——所以这个问题可能对像我这样的其他人仍然有用 原始问题:假设我有以下数据结构,表示我的用户界面中的一项: public static abstract class RowItem<T> {

编辑:是,这可能是重复的。但是,另一个问题类似于“什么是电锯,我该如何使用它?”我的问题更像是“我正试图用这台机器在这里钻孔,但它不起作用-怎么了?”。当然,答案是“不要使用电锯!”一旦你知道你正在使用电锯,就很容易找到

但我甚至不知道我的问题与“原始类型vs.通配符”有关,因此没有发现这个问题——所以这个问题可能对像我这样的其他人仍然有用

原始问题:假设我有以下数据结构,表示我的用户界面中的一项:

public static abstract class RowItem<T> {

    public final T value;

    public RowItem(T value) {
        this.value = value;
    }
}
我觉得编译器应该知道
epgRowItem.value
必须始终是
,因此
epgRowItem.value。首先
必须始终是
字符串

事实上,它甚至不知道第一部分,我。E以下内容也不会编译:

Pair<String, ?> pair = epgRowItem.value; // epgRowItem.value is an Object?!
Pair Pair=epgRowItem.value;//epgRowItem.value是对象吗?!

我做错了什么?我是不是对Java的泛型要求太多了?

您遇到了麻烦,因为您使用的是原始类型
EpgRowItem
(原始类型是一种参数化类型,您没有为其指定类型参数;这些类型的存在是因为与Java 1.4及更早版本的向后兼容性):

列出程序=。。。;
OverlyPresenter.EpgRowItem EpgRowItem=programs.get(0);
见:

使用类型参数,或至少使用通配符:

List<OverlayPresenter.EpgRowItem<?>> programs = ...;
OverlayPresenter.EpgRowItem<?> epgRowItem = programs.get(0);
String channelId = epgRowItem.value.first;  // OK
List epgRowItem=programs.get(0);
字符串channelId=epgRowItem.value.first;//好啊

哦,这很有趣。到目前为止,我一直觉得使用Java泛型很安全,但这对我来说是新的。非常感谢你!是的,既然我知道答案,那当然是重复的。但既然我问了“另一个问题”——从一个具体的问题开始,而不是一个高层次的关键词——我认为这仍然是一个有效的问题,可能对其他人有用。
Pair<String, ?> pair = epgRowItem.value; // epgRowItem.value is an Object?!
List<OverlayPresenter.EpgRowItem> programs = ...;
OverlayPresenter.EpgRowItem epgRowItem = programs.get(0);
List<OverlayPresenter.EpgRowItem<?>> programs = ...;
OverlayPresenter.EpgRowItem<?> epgRowItem = programs.get(0);
String channelId = epgRowItem.value.first;  // OK