A generic Java interface with one parameter has actually two
I recently found Java code similar to this:
public interface DemoInterface<T> extends Serializable
{
<V> void demoMethod(Collection<V> someValues, SomeType<V, T> moreValues);
}
Since I've already read some interface tips and never found a situation like this, I'm asking here: in the interface statement it mentions <T>
. What does it mean <V>
?
If you know the answer, please be patient and give an example how to use this interface and implementation of the interface and demoMethod.
Thank.
+3
source to share
2 answers
I just offer an example:
DemoInterface<Type> demo = new DemoInterface<>() {
<V> void demoMethod(Collection<V> someValues, SomeType<V, Type> moreValues) {
Type type = new Type();
foreach(V value: someValues) {
Type subtype = moreValues.doSomething(value);
type.concat(subtype);
}
System.out.printf("result: %s%n", type);
}
};
SomeType<ValueA, Type> someA = new SomeType<>();
SomeType<ValueB, Type> someB = new SomeType<>();
List<ValueA> listA = new Arraylist<>(); // add some elements
List<ValueB> listA = new Arraylist<>(); // add some elements
demo.demoMethod(listA, someA);
demo.demoMethod(listB, someB);
+1
source to share