gpt4 book ai didi

java - Bruce Eckel 的 "Thinking in Java"中的这个泛型示例是否错误?

转载 作者:行者123 更新时间:2023-11-29 03:15:47 24 4
gpt4 key购买 nike

我正在阅读“Thinking in java”中的泛型章节。该程序在下面。

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(); }
}

下面它说“writeExact( ) 方法使用精确的参数类型(无通配符)。在 f1( ) 中你可以看到它工作正常——只要你只将 Apple 放入 List<Apple> 中。然而, writeExact( ) 不允许您将 Apple 放入 List<Fruit> 中,即使您知道这应该是可能的。”

但是当我取消注释第 1 行并执行它时,它工作正常。谁能帮我解决我哪里出错了?

最佳答案

However, writeExact( ) does not allow you to put an Apple into a List<Fruit>, even though you know that should be possible.

这是不正确的。 writeExact可以放一个AppleList<Fruit> . <T>推断为 FruitApple (大概)是 Fruit 的子类型.

这本书有一个错误。我可以确认,当引入泛型时,这将在 Java 5 中编译。

关于java - Bruce Eckel 的 "Thinking in Java"中的这个泛型示例是否错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26747867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com