Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface implementations with different concrete types as method parameters

Tags:

java

generics

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)

like image 458
beginner_ Avatar asked Mar 19 '26 00:03

beginner_


1 Answers

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>();
   }
}
like image 135
Hovercraft Full Of Eels Avatar answered Mar 20 '26 12:03

Hovercraft Full Of Eels