T
T
thatmaniscool2017-06-11 21:25:57
Java
thatmaniscool, 2017-06-11 21:25:57

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);
}

Then I create a demo class
public class DemoClass {
  private int id;
  public DemoClass (int id){
    this.id = id;
  }
}

I create a class that implements the interface and parameters.
public class GenericClass implements Generator <DemoClass, Integer>{
  public DemoClass next(Integer x) {
    return new DemoClass (x);
  }
}

Now I'm creating a class with a generic method and here comes the problem, namely, I can't pass two parameters at the same time. How to do it right?
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);
  }
}

, how to correctly set the parameters passed to the generic method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Oparin, 2017-06-12
@losse_narmo

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 question

Ask a Question

731 491 924 answers to any question