How to Create a Generic List in Java?
Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter. Generics can be used to build classes that interact with various data types. A generic entity is one that works on a parameterized type, such as a class, interface, or function.
Why Use Generics?
All other classes are subclasses of the Object, and an Object reference can be used to refer to any object. It lacks type safety in several features. That kind of safety feature is added by generics. Later examples will cover this kind of safety feature.
In Java, generics resemble C++ templates. For instance, generics are effectively used by classes like HashSet, ArrayList, HashMap, etc. The two methods of dealing with generic types have several key distinctions.
Types of Java Generics
- Generic Method: A generic Java method performs an operation and then returns some value. Similar to a conventional function, a generic method includes type arguments that are listed according to the actual type. This enables a broader application of the generic technique. Because the compiler handles type safety, programmers can write code more quickly because they are not required to do time-consuming, individual type casts.
- Generic classes: Classes that are generic are implemented exactly like classes that are not generic. The presence of a type parameters section is the only distinction. There may be different parameter types, each distinguished by a comma. The classes are referred to as parameterized classes as well as parameterized types if they receive one or more parameters.
We utilize <> to define argument types when creating generic classes, just like in C++. The syntax used to generate instances of the generic class is as follows.
// To create a generic class instance
class Test<T> {
T obj;
Test(T obj) { this.obj = obj; }
public T getObject() { return this.obj; }
}
class Main {
public static void main(String[] args)
{
Test<Integer>iObj = new Test<Integer>(11);
System.out.println(iObj.getObject());
Test<String>sObj
= new Test<String>("\nHello people");
System.out.println(sObj.getObject());
}
}
Output
11
Hello people
In Generic classes, we may also pass numerous Type parameters.
class Test<T, U>
{T obj1;
U obj2;
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
class Main
{
public static void main (String[] args){
Test <String, Integer>obj =
new Test<String, Integer>("javatpoint", 11);
obj.print();
}
}
Output
Javatpoint
11
- Generic Functions: Depending on the type of arguments supplied to the generic method, we can also create generic functions that may be invoked with various sorts of arguments. Each method is handled by the compiler.
class Test {
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getName()
+ " = " + element);
}
public static void main(String[] args)
{
genericDisplay(12);
genericDisplay("java t point");
genericDisplay(2.0);
}
}
Output
java.lang.Integer = 12
java.lang.String = java t point
java.lang.Double = 2.0
Only reference types can be used with generics:
The type argument supplied towards the type parameter when declaring an implementation of a generic type should be a reference type. Primitive data types like int and char are not allowed.
Test<int>obj = new Test<int>(20);
Utilizing type wrappers to enclose a primitive type will fix the compile-time error caused by the aforementioned line.
Arrays, however, are reference types, therefore they can be provided as the type argument along with arrays of primitive types.
ArrayList<int[]> a = new ArrayList<>();
Creation of a Generic List in Java
In the List interface, Java has offered generic support.
Syntax
List<T> list = new ArrayList<T>();
Where
The object of the List interface is a list.
T is the generic type argument used to declare lists.
Description
The generic interface Lists and its implementation class ArrayList both accept the type parameter T.
Program
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericsTester {
public static void main(String[] args) {
List<Integer>integerList = new ArrayList<Integer>();
integerList.add(Integer.valueOf(10));
integerList.add(Integer.valueOf(11));
List<String>stringList = new ArrayList<String>();
stringList.add("Hello People");
stringList.add("Hi People");
System.out.printf("Integer Value :%d\n", integerList.get(0));
System.out.printf("String Value :%s\n", stringList.get(0));
for(Integer data: integerList) {
System.out.printf("Integer Value :%d\n", data);
}
Iterator<String>stringIterator = stringList.iterator();
while(stringIterator.hasNext()) {
System.out.printf("String Value :%s\n", stringIterator.next());
}
}
}
Output
Integer Value: 10
String Value: Hello People
Integer Value: 10
Integer Value: 11
String Value: Hello People
String Value: Hi People