×

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

  1. 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.
  2. 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

Related Topics

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 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.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

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.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.