Reputation: 11
I have the following class
public class Element <T1 extends Comparable<T1>,T2> {
public T1 key;
public T2 value;
}
This compiles and works as I'd like.
I have an interface that I want to guarantee that all Elements in it have the same type. But I want to specify that type in the class implementing the interface. So as an example, I might want the class that implements the interface to all be of the type Element<String,Integer>
.
However, this won't compile
public interface D <Element<T1,T2>> {
ArrayList <Element<T1,T2>> getVertices();
}
This does compile
public interface D <Element> {
ArrayList <Element> getVertices();
}
When I run this code
public class G<Element> implements D<Element> {
public ArrayList<Element> getVertices(){return null;}
public static void main(String[] args) {
G <Element<String,Integer>> g = new G<>();
}
}
I get this error. 'Error:(7, 12) java: non-static type variable Element cannot be referenced from a static context'
I'm not sure how to specify in the interface that I want all elements to have to be of the same type.
Upvotes: 1
Views: 85
Reputation: 5948
The T1
and T2
in your D
interface are undefined, thats why you are getting compile error. The second D
example is using row type of Element and thats why your G <Element<String,Integer>>
declaration is wrong. Also you dont need to parametrize G
at all.
Here is modified code that uses proper generics:
public interface D < T1 extends Comparable<T1>, T2 > {
ArrayList < Element<T1, T2> > getVertices();
}
public static class G implements D< String, Integer > {
public ArrayList< Element<String, Integer> > getVertices(){return null;}
public static void main(String[] args) {
G g = new G();
}
}
Upvotes: 2