泛型方法的Eclipse编译错误

时间:2014-09-10 09:50:13

标签: java eclipse generics compiler-errors

我在使用通用方法时在Eclipse中遇到编译错误,这在使用javac时不会出现。我猜它是Eclipse中的编译器选项,但我在Preferences窗口中看不到相关项。

我正在使用的示例来自Thinking In Java第4版,相关代码如下,复制并粘贴自本书网站的可下载示例。

//: generics/Generators.java
// A utility to use with Generators.
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);  }
}

GeneratorCoffeeCoffeeGenerator在其他地方定义,但我不相信它们与我的问题相关。

此代码给出了编译器错误:'Generators类型中的方法fill(Collection,Generator,int)不适用于参数(ArrayList,CoffeeGenerator,int)'。

我可以更改哪些选项以使Eclipse编译与从命令行使用javac时相同?

非常感谢提前!我确实做过搜索(这里和谷歌)并且找不到答案 - 如果这是重复的话,道歉。

CoffeeGenerator代码:

//: generics/coffee/CoffeeGenerator.java
// Generate different types of Coffee:
import java.util.*;
import net.mindview.util.*;

public class CoffeeGenerator
implements Generator<Coffee>, Iterable<Coffee> {
  private Class[] types = { Latte.class, Mocha.class,
    Cappuccino.class, Americano.class, Breve.class, };
  private static Random rand = new Random(47);
  public CoffeeGenerator() {}
  // For iteration:
  private int size = 0;
  public CoffeeGenerator(int sz) { size = sz; } 
  public Coffee next() {
    try {
      return (Coffee)
        types[rand.nextInt(types.length)].newInstance();
      // Report programmer errors at run time:
    } catch(Exception e) {
      throw new RuntimeException(e);
    }
  }
  class CoffeeIterator implements Iterator<Coffee> {
    int count = size;
    public boolean hasNext() { return count > 0; }
    public Coffee next() {
      count--;
      return CoffeeGenerator.this.next();
    }
    public void remove() { // Not implemented
      throw new UnsupportedOperationException();
    }
  };    
  public Iterator<Coffee> iterator() {
    return new CoffeeIterator();
  }
}

生成器代码:

//: net/mindview/util/Generator.java
// A generic interface.
package net.mindview.util;
public interface Generator<T> { T next(); } ///:~

0 个答案:

没有答案