0


假设我假设扩展LinkedList以创建一个名为GroceryList.

GroceryList用类GroceryItem作为它的类型进行参数化。

当我尝试在GroceryItem中作为实例访问时GroceryList,在 NetBeans 中出现此编译错误:

incompatible types
 Required: GroceryItem
 Found:    Object
 where GroceryItem is a type-variable
   GroceryItem extends Object declared in class GroceryList


显然这是由于“类型擦除”,到目前为止,我没有成功地以这种方式将一个类用作“类型变量”和一个类......



这是一个简单的例子:

public class GroceryList<GroceryItem> extends LinkedList {

    public GroceryList() {
    }

    public double getItemPrice(GroceryItem item) {

        // compile-error occurring here:
        return item.getPrice();
    }

    // compile-error occurring here:
    public GroceryItem getGroceryItem(String name, String brand, double price) {

        // ...finding the grocery item based on the parameters here:
        // ...

        return item;
    }
} // end of class
4

1 回答 1

3

扩展LinkedList使用GroceryItem类型

public class GroceryList extends LinkedList<GroceryItem>

或使用以下方法将类定义为泛型:

public class GroceryList<T extends GroceryItem> extends LinkedList<T>
于 2013-09-28T20:36:02.170 回答