这是来自Bruce Eckel的“Thinking in Java”的仿制药示例吗?错误? [英] Is this generics example from Bruce Eckel's "Thinking in Java" wrong?
问题描述
我正在阅读Thinking in java中的泛型章节。该计划如下。
公共类GenericWriting {
static< T> void writeExact(List< T> list,T item){
list.add(item);
}
静态列表< Apple> apples = new ArrayList< Apple>();
静态列表< Fruit> fruit = new ArrayList< Fruit>();
static void f1(){
writeExact(apples,new Apple());
// writeExact(fruit,new Apple()); //错误:------------------第1行
//不兼容的类型:找到水果,必需Apple
}
static< T> void writeWithWildcard(List<?super T> list,T item){
list.add(item);
}
static void f2(){
writeWithWildcard(apples,new Apple());
writeWithWildcard(fruit,new Apple());
}
public static void main(String [] args){f1(); F2(); }
}
下面写着writeExact()方法使用精确的参数类型(没有通配符)。在f1()中你可以看到这个工作正常 - 只要你把Apple放到 List< Apple>
中。但是,writeExact()会不允许您将Apple放入列表< Fruit>
,即使您知道应该可以。
<但是当我取消注释第1行并执行它时,它工作正常。任何人都可以在我出错的地方帮助我吗?
然而,
writeExact()
不允许您将Apple
放入列表< Fruit>
,即使你知道这应该是可能的。
这是不正确的。 writeExact
可以将 Apple
放入列表< Fruit>
。 < T>
被推断为水果
和 Apple
(推测)是 Fruit
的子类型。
该书包含错误。我可以确认,这将在Java 5中编译,当引入泛型时。
I am reading the generics chapter in "Thinking in java". The program is there below.
public class GenericWriting {
static <T> void writeExact(List<T> list, T item) {
list.add(item);
}
static List<Apple> apples = new ArrayList<Apple>();
static List<Fruit> fruit = new ArrayList<Fruit>();
static void f1() {
writeExact(apples, new Apple());
// writeExact(fruit, new Apple()); // Error:------------------line 1
// Incompatible types: found Fruit, required Apple
}
static <T> void writeWithWildcard(List<? super T> list, T item) {
list.add(item);
}
static void f2() {
writeWithWildcard(apples, new Apple());
writeWithWildcard(fruit, new Apple());
}
public static void main(String[] args) { f1(); f2(); }
}
Below it says "The writeExact( ) method uses an exact parameter type (no wildcards). In f1( ) you can see that this works fine—as long as you only put an Apple into a List<Apple>
. However, writeExact( ) does not allow you to put an Apple into a List<Fruit>
, even though you know that should be possible."
But when I uncomment the line 1 and execute it, it is working fine. Can anyone please help me where I went wrong?
However,
writeExact( )
does not allow you to put anApple
into aList<Fruit>
, even though you know that should be possible.
This is incorrect. writeExact
can put an Apple
in to a List<Fruit>
. <T>
is inferred to be Fruit
and Apple
(presumably) is a subtype of Fruit
.
The book contains an error. I can confirm that this will compile as of Java 5, when generics were introduced.
这篇关于这是来自Bruce Eckel的“Thinking in Java”的仿制药示例吗?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!