×

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

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

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

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.