1

Possible Duplicate:
Java how to: Generic Array creation

I wanna create something like this:

public class MyClass<T> {
    private int row;
    private int column;
    private T[][] result;

    public T[][] generation(int size, T[] values) {
        result = new T[values.length][size];

        generator(0, 0);

        return result;
    }
}

But I'm gettin an error "generic array creation", how can I fix that? :(

Community
  • 1
  • 1
ruslanys
  • 1,093
  • 2
  • 13
  • 25

3 Answers3

5

If you can get the type of T i.e. Class<T>, you can utilize Array.newInstance as follows...

public T[][] generation(int size, T[] values) {
  result = (T[][]) Array.newInstance(values.getClass().getComponentType(),
      values.length, size);
  generator(0, 0);
  return result;
}
obataku
  • 27,809
  • 3
  • 38
  • 50
  • 1
    You could also use `values.getClass().getComponentType()` instead of having to pass in `type`. – Paul Bellora Sep 08 '12 at 05:30
  • Thanks, I was able to write a functional java BiFunction that converts a Generic list of lists into a generic bidimensional array as follows: `BiFunction>, Class,T[][]> toArray = (list,type) -> { T a[][] = (T[][]) Array.newInstance(type, list.size(), list.get(0).size()); IntStream.range(0, a.length).forEach(i -> { a[i]=(T[]) list.get(i).toArray(); }); return a; };` – Gabriel Hernandez Apr 08 '19 at 17:19
1

new T is not possible, you have to use Object and cast before returning or after returning

Primitives are also not possible you have to use Integer, Float, etc.

zeyorama
  • 428
  • 3
  • 12
0

java.lang.reflect.Array.newInstance is exactly what you need.

You only need an object of Class<T> but you could take one in the constructor of your class.

main--
  • 3,672
  • 13
  • 35
  • I saw the some topic but with one dimensional array. Can not understand how to get instance of multidimensional array. – ruslanys Sep 07 '12 at 19:19