×

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

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.