关于《Java 编程思想》第四版第十五章“泛型”逆变例子的疑惑



在ITeye上看到一个问题

问题原帖地址:http://www.iteye.com/topic/164966

《Java 编程思想》15.10.2 逆变例子如下: (393页)
public class Fruit {}
public class Apple extends Fruit {}

//: generics/GenericWriting.java
import java.util.*;

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:
    // 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(); }
} ///:~
//=================================
红色部分按书上说明应该编译出错,可是我试了一下,可以通过编译,不知是什么问题。

 

iteye某人的回答真是。。。

后来鄙人上SOF上搜寻答案,发现还真有

答案原帖地址:

http://stackoverflow.com/questions/26747867/is-this-generics-example-from-bruce-eckels-thinking-in-java-wrong/26747956#26747956

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

This is incorrect. writeExact can put an Apple in to aList<Fruit>. <T> is inferred to be Fruit andApple (presumably) is a subtype of Fruit.

You should check the Java version that your book is written for. It may be that in an older version of Java this would not compile due to less inference on the part of the compiler. Otherwise the book contains an error.

This will compile as of Java 6+ that I can confirm.

 

感觉是Java版本的问题,毕竟作者用的Java SE5.我用的是Java 7.

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值