Vance-Turner Vance-Turner - 3 months ago 19
Java Question

Instantiating Generic Type in class: V extends List

I'm trying to develop a class that works with objects who extend java.util.List, for example, ArrayList. Below is an example of what I think should compile (assuming the necessary import statements):

public class MyClass<V extends List> {

V myList = new ArrayList();

MyClass<ArrayList> myinstance = new MyClass<>();
}


While the "myinstace" is no problem, the compiler fails when attempting to instantiate "myList.":


MyClass.java:[17,16] incompatible types: java.util.ArrayList cannot be
converted to V


As I understand generics, declaring:

<V extends List>


implies that whatever type "V" is, it must be a subclass of "List." Thus, why cannot I instantiate as above, and is there any correct way to instantiate an object of type "V" within the class?

Furthermore, how might one return an object of type "V" within a method in the class?

public V getSomeData(){
// How do we create our object of type "V"?
}


Background

I have an interface, PatternElement:

public interface PatternElement<D,W> {

/**
* The data that this element contains or signifies.
* @return
*/
public D getData();

/**
* The width of this pattern element within a pattern.
* @return
*/
public W getWidth();

}


I'm trying to develop a subclass, PolyPatternElement, which can contain many "data" and "width" items within itself. I thought the following code would accomplish this...

public class PolyPatternElement<V extends List, W extends List> implements PatternElement<V,W>{


@Override
public V getData() {
ArrayList data = new ArrayList();
return data;
}

@Override
public W getWidth() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}


Unfortunately, "getData" doesn't compile. Thus, I narrowed down the problem and asked the original question. After the feedback, I think the better PolyPatternElement definition is:

public class PolyPatternElement<V,W> implements PatternElement<List,List>{


@Override
public List getData() {
ArrayList data = new ArrayList();
return data;
}

@Override
public List getWidth() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}


This allows declaring a PolyPatternElement object whose types are any implementation of List which was my intention.

Answer

Try (untested):

public class PolyPatternElement<V, W> implements PatternElement<List<V>, List<W>>
Comments