//: generics/Generators.java
// A utility to use with Generators.
import generics.coffee.*;
import java.util.*;
import net.mindview.util.*;public class Generators {
  public static <T> Collection<T>
  fill(Collection<T> coll, Generator<T> gen, int n) {
    for(int i = 0; i < n; i++)
      coll.add(gen.next());
    return coll;
  }
  public static void main(String[] args) {
    Collection<Coffee> coffee = fill(
      new ArrayList<Coffee>(), new CoffeeGenerator(), 4);
    for(Coffee c : coffee)
      System.out.println(c);
    Collection<Integer> fnumbers = fill(
      new ArrayList<Integer>(), new Fibonacci(), 12);
    for(int i : fnumbers)
      System.out.print(i + ", ");
  }
} /* Output:
Americano 0
Latte 1
Americano 2
Mocha 3
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
*///:~main方法中的那个ArrayList<Coffee>中的类型参数Coffee为什么不能省略?(现在的情况是省略后报警告)

解决方案 »

  1.   

    new CoffeeGenerator() 中的类型参数不就省略了。
      

  2.   

    如果不用泛型,存放进去的和取出的都是object类型。
    把父类赋给子类,会有警告。
      

  3.   

    Collection <Coffee> coffee = fill(.你是这样声明的啊,当然不能省
      

  4.   

    但是我同样声明了Generator <T> gen 但是在new CoffeeGenerator()中没有加类型参数啊!
      

  5.   

    你可以省略 但是省略了 在取出容器里的元素时 需要强制转换成Coffee类型了
      

  6.   


    coffee 是Collection  <Coffee>类型的, fill(. 返回的是Collection类型的。
    要类型转换
      

  7.   

    这个是可以省略的。。jdk15之后就有了泛型,它帮你来纠正类型强制转换错误吧。。起到这样的一个好处