×

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 SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.