0

In my Java program I have a method that needs to return a generic array. In order to simplify things, I have made a much simpler code to reproduce my problem, which is the following:

public class Main {
    public static void main(String[] args) {
        Integer[] integers = toArray(1); 
        System.out.println(integers [0]); //should output 1
    }

    public static <T> T[] toArray(T element) {
        T[] array = (T[]) new Object[1];
        array[0] = element;
        return array;
    }
}

But when I execute this code I get the following exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at Main.main(Main.java:3)

But if I change the type of integers to Object[], it works as expected. I suppose it's due to the fact that Java only supports generics at compile time, and then performs type erasure, transforming in this case my Integer array to a Object array.

But my problem persists, and my method must return a collection of generic T values, whether the return value is a List or an array it's the same, so if it's not possible to accomplish what I want with an array, I could use an ArrayList, for example.

But... is it possible to accomplish this simply by using an array?

Thank you.

Jose Luis
  • 929
  • 1
  • 8
  • 21
fergaral
  • 1,929
  • 6
  • 14
  • 31

0 Answers0