Answer the question
In order to leave comments, you need to log in
How to correctly pass a double parameter to a Java generic method?
First of all I create an interface with two parameters.
public interface Generator <T, R> {
public T next (R x);
}
public class DemoClass {
private int id;
public DemoClass (int id){
this.id = id;
}
}
public class GenericClass implements Generator <DemoClass, Integer>{
public DemoClass next(Integer x) {
return new DemoClass (x);
}
}
import java.util.*;
public class MainClass {
private static Random rand = new Random ();
public static <T> T [] arr (T [] a, Class <?> typeToken){
try{
Generator <?, ?> gen = (Generator <?, ?>)typeToken.newInstance(); // Как передать два параметра.
for (int i=0; i!=a.length; i++){
a[i] = (T) gen.next(rand.nextInt(100)); // Эта строчка не работает.
}
} catch (Exception e){
throw new RuntimeException (e);
} return a;
}
public static void main (String [] args){
@SuppressWarnings("unused")
DemoClass [] myarr = arr (new DemoClass[10], GenericClass.class);
}
}
Answer the question
In order to leave comments, you need to log in
Because the parameter is not of the expected type:
(T) ((Generator<?, Integer>) gen).next(rand.nextInt(100)); // Эта строчка уже работает.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question