×

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

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.