×

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.

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.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

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.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.