I would like to have a method in an interface that accepts any Type of a generic object, like
public void myMethod(List<?>);
Now the implementations should only accept a certain type, eg. implementations 1:
public void myMethod(List<Integer>);
Implementation 2:
public void myMethod(List<String>);
However this does not work as public void myMethod(List<Integer>); is not a valid implementaion of public void myMethod(List<?>);
How could I achieve this? (Besides using an Object Parameter and hence rely on casting and do type checking manually)
Unless I'm missing something obvious (which happens too much for my liking), why not make the interface itself generic?
public interface MyInterface<T> {
public void myMethod(List<T> list);
}
Which can be implemented like so:
public class MyClass<T> implements MyInterface<T> {
@Override
public void myMethod(List<T> list) {
// TODO complete this!
}
}
and used like so:
public class Foo {
public static void main(String[] args) {
MyClass<String> myString = new MyClass<String>();
MyClass<Integer> myInt = new MyClass<Integer>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With