×

Java Array Generic

Creating Generic Array in Java

A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's items is used at runtime to allocate memory. However, because of type erasing, this information is not accessible in the case of generics.

Generic classes, methods, and other constructs can be declared in Java and are type-independent. Java, however, prohibits the Array from being generic. This is because arrays in Java contain data on their constituent parts, which is utilized to allocate memory at runtime.

Generics look for type information at compile time, and no information is accessible at runtime.

Because arrays are covariant, the type information is verified at runtime. It implies that we can link an array of child types to a parent type (like String[] to Object[]).

String[] Arrayofstring = new String[24];
Object[] Arrayofobject = Arrayofstring; //No Error

There will be no compile-time errors returned by the code above. Without the concern of compilation issues, we can add more items to the aforementioned Array. But for arrays, type verification is done at runtime for each element. ArrayStoreExceptions are thrown if any errors are discovered during runtime.

Program.java

public class Program
{
	public static void main(String[] args)
	{
		String[] Arrayofstring = new String[24];
		Object[] Arrayofobject = Arrayofstring; //No Error
		Arrayofobject[0] = new Object();
		Arrayofobject[1] = new Exception();
	}
}

Output:

Java Array Generic

Instead of using generic arrays, it is advised to utilize Collection Frameworks like the List. However, we can build a generic array if we know something about the type at compile time. Let's examine the Java process for making a generic array.

Creating a Generic Array Using Object Array

We may make a generic class with an Object array to resemble a generic array. We will employ the get() and set() methods in this class. An explicit cast will be used in the get() function.

GenericArrayJava.java

import java.util.Arrays;
class GenericArrayJava<T>
{
	private Object[] Arrayofgeneric;
	GenericArrayJava(int size)
	{
		Arrayofgeneric = new Object[size];
	}	
	public T get(int index)
	{
		return (T) Arrayofgeneric[index];
	}	
	public void set(int index, T element)
	{
		Arrayofgeneric[index] = element;
	}	
	@Override
    public String toString()
	{
        return Arrays.toString(Arrayofgeneric);
    }
}
public class Demo
{
	public static void main(String[] args)
	{
		GenericArrayJava<String> Arrayofstring = new GenericArrayJava(3);
		Arrayofstring.set(0, "seven");
		Arrayofstring.set(1, "twelve");
		Arrayofstring.set(2, "twenty four");		
		GenericArrayJava<Integer> Arrayofinteger = new GenericArrayJava(3);
		Arrayofinteger.set(0, 21);
		Arrayofinteger.set(1, 12);
		Arrayofinteger.set(2, 32);		
		GenericArrayJava<Double> Arrayofdouble = new GenericArrayJava(3);
		Arrayofdouble.set(0, 21.0);
		Arrayofdouble.set(1, 12.0);
		Arrayofdouble.set(2, 32.0);		
		System.out.println("Array of Integer: " + Arrayofinteger);
		System.out.println("Array of String: " + Arrayofstring);
		System.out.println("Array of Double: " + Arrayofdouble);
	}
}

Output:

Java Array Generic

If we don't provide consumers direct access to the object array and instead utilize the get() and set() functions, the preceding strategy works just great. It should be noted that even the ArrayList stores its elements in an object array. ArrayLists cannot directly access this object array.

Creating a Generic Array Using Reflection

This method is identical to that described in the previous part. The only distinction is that the type information will be provided by the function Object(), and our Array will then be initialized using the Array.newInstance() function. The following illustrates the whole implementation.

GenericArrayJava.java

import java.lang.reflect.Array;
import java.util.Arrays;
class GenericArrayJava<T>
{
	private T[] Arrayofgeneric;
	
	GenericArrayJava(Class<T> classType, int size)
	{
		Arrayofgeneric = (T[]) Array.newInstance(classType, size);
	}	
	public T get(int index)
	{
		return Arrayofgeneric[index];
	}	
	public void set(int index, T element)
	{
		Arrayofgeneric[index] = element;
	}	
	@Override
    public String toString()
	{
        return Arrays.toString(Arrayofgeneric);
    }
}
public class Demo
{
	public static void main(String[] args)
	{
		GenericArrayJava<String> Arrayofstring = new GenericArrayJava(String.class, 3);
		Arrayofstring.set(0, "seven");
		Arrayofstring.set(1, "twelve");
		Arrayofstring.set(2, "twenty four");
		
		GenericArrayJava<Integer> Arrayofinteger = new GenericArrayJava(Integer.class, 3);
		Arrayofinteger.set(0, 21);
		Arrayofinteger.set(1, 12);
		Arrayofinteger.set(2, 32);
		
		GenericArrayJava<Double> Arrayofdouble = new GenericArrayJava(Double.class, 3);
		Arrayofdouble.set(0, 21.0);
		Arrayofdouble.set(1, 12.0);
		Arrayofdouble.set(2, 32.0);
		
		System.out.println("Array of Integer: " + Arrayofinteger);
		System.out.println("Array of String: " + Arrayofstring);
		System.out.println("Array of Double: " + Arrayofdouble);
	}
}

Output:

Java Array Generic

Conclusion

Generic classes can be used to implement generic arrays in Java. We can allow the user to interact with this generic Array using an Object array and the proper methods. The ArrayList class likewise employs the idea of an object array. We can also have the user supply the type information to the function Object() using the Array.newInstance() function. Generic methods of other Collections, like the LinkedList, take a similar tack. It is often advised to utilize array lists or linked lists rather than building our generic lists.


Related Topics

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.