Search code examples
javacollectionscompiler-errorstype-erasure

If I use a class as a type parameter, how can I create an instance of this object within the parameterized class?



Say I hypothetically extend LinkedList to create a specialized sub-class called GroceryList.

GroceryList is parameterized with the class GroceryItem as its' type.

When I try to access GroceryItem as an instance within GroceryList, I get this compile-error in NetBeans:

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


Apparently this is due to "type-erasure", and so far I'm unsuccessful in using a class as both a "type-variable" and a class in this way...



Here is a simple example:

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

Solution

  • Extend the LinkedList using the GroceryItem type

    public class GroceryList extends LinkedList<GroceryItem>
    

    or define the class as generic using:

    public class GroceryList<T extends GroceryItem> extends LinkedList<T>