Open In App

How to Create a Generic Array in Java?

Arrays in Java are generated using a certain data type. On the other hand, you may create a generic array that functions with various object types by utilizing generics. You can build type-safe, reusable code by using generics. In this article, we will learn about creating generic arrays in Java.

Creating Generic Array in Java

Java’s generics let you write methods, interfaces, and classes that take in and use many kinds of arguments. Usually, while creating the class or function, you’ll utilize the generic type to construct a generic array.



Generic Class with Array

Below is the implementation of creating a generic class with an array:




public class GenericArray<T> {
    private T[] array;
  
    public GenericArray(int size) {
        // Creating a generic array using reflection
        array = (T[]) new Object[size];
    }
  
    public void setElement(int index, T value) {
        array[index] = value;
    }
  
    public T getElement(int index) {
        return array[index];
    }
  
    public static void main(String[] args) {
        GenericArray<String> stringArray = new GenericArray<>(5);
        stringArray.setElement(0, "Java");
        stringArray.setElement(1, "is");
        stringArray.setElement(2, "awesome");
  
        System.out.println("Element at index 1: " + stringArray.getElement(1));
    }
}

Output

Element at index 1: is

Generic Method with Array

Below is the implementation of Generic Method with Array:




import java.lang.reflect.Array;
import java.util.Arrays;
  
public class GenericArrayExample {
    @SuppressWarnings("unchecked")
    public static <T> T[] createArray(int size, T defaultValue) {
        // Creating a generic array using reflection
        T[] array = (T[]) Array.newInstance(defaultValue.getClass(), size);
        Arrays.fill(array, defaultValue);
        return array;
    }
  
    public static void main(String[] args) {
        Integer[] intArray = createArray(5, 0);
        System.out.println("Integer Array: " + Arrays.toString(intArray));
  
        String[] strArray = createArray(3, "Hello");
        System.out.println("String Array: " + Arrays.toString(strArray));
    }
}

Output
Integer Array: [0, 0, 0, 0, 0]
String Array: [Hello, Hello, Hello]


Article Tags :