-1

i want to make array with using generices.
but compile error occurred.
How to make array with using generices?

public class Test {

    public static void main(String[] args) {
        String[] datas = Test.changeToArray("apple");
        for (String data : datas) {
            System.out.println(data);
        }
        Boolean[] bools = Test.changeToArray(true);
        for (Boolean bool : bools) {
            System.out.println(bool);
        }
    
    }

    public static <T> T[] changeToArray(T data) {
        // i want this..
        // but this is compile error
        // Cannot create a generic array of T
        T[] datas = new T[] {data};
        return datas;
    }

}
bittap
  • 518
  • 1
  • 6
  • 15
  • Does this answer your question? [What's the reason I can't create generic array types in Java?](https://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java) – Progman May 30 '21 at 11:14

1 Answers1

1

Please go through the restrictions on generics. Its not allowed to create arrays of parameterize types in java. See java docs.

pcsutar
  • 1,715
  • 2
  • 9
  • 14