How to create a generic array in Java?

 

Creating a generic array directly in Java is not straightforward due to type erasure – the fact that generic type information is not available at runtime. While you can create an array of a specific type (e.g., String[], Integer[], etc.), creating a truly generic array is not directly supported.

However, you can achieve similar functionality using collections like ArrayList or by using reflection to create arrays. Here's an example using ArrayList:

java
import java.util.ArrayList; import java.util.List; public class GenericArrayExample { public static <T> List<T> createGenericList(T... elements) { List<T> list = new ArrayList<>(); for (T element : elements) { list.add(element); } return list; } public static void main(String[] args) { List<String> stringList = createGenericList("Hello", "World"); List<Integer> integerList = createGenericList(1, 2, 3); System.out.println("String List: " + stringList); System.out.println("Integer List: " + integerList); } }

In this example:

  • The createGenericList method uses a varargs parameter to allow the creation of a generic list of elements.
  • The method takes elements of any type and creates a List<T> containing those elements.

Using collections like ArrayList is a common and recommended approach to work with collections of generic elements in Java. It provides type safety and avoids the complications associated with creating true generic arrays.

Comments