×

Generics in Java

Generics in Java

Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java facilitate the creation of classes that deal with different types of datatypes. Entities, such as methods, interfaces, classes that act on the parameterized type,are known as the generic entity. Generics is similar to template C++ templates.

Need of Generics in Java

We know that theObject class is the parent class of all the Java classes, and hence,it is obvious that the Object reference can refer to any object. These features do not ensure type safety.To achieve the same in Java, we use Generics.

Generics Class in Java

Similar to C++, we use angular brackets (<>) to mention parameter types in the creation of the generic class.

Syntax:

 // For creating an object of a generic class
GenericClass<T> obj = new GenericClass<T>();
Where T refers to parameter type such as String, Character, Integer, etc. 

Note: In the parameter,use of primitive type is not allowed. For example, 'char', 'int', 'float', 'double'

Generics Class Examples

FileName: GenericsExample.java

 // A Java program that shows the working of the user-defined
// Generic class
// We use <> to specify Parameter type
class ABC<Type>
{
// Declaring an object of type "Type"
Type obj;
// constructor of the class ABC
ABC(Type obj)
{
    this.obj = obj;
}
// returning the object
public Type getObject()
{
return this.obj;
}
}
public class GenericsExample
{
// main method
public static void main (String argvs[])
{
// An instance of the Integer type
ABC <Integer> intObj = new ABC<Integer>(17);
System.out.println("The value of the integer is: " + intObj.getObject());
// An instance of the String type
ABC <String> strObj = new ABC<String>("Tutorial & Example");
System.out.println("The value of the string is: " + strObj.getObject());
// An instance of the Float type
ABC <Float> floatObj = new ABC<Float>(9.9f);
System.out.println("The value of the float is: " + floatObj.getObject());
// An instance of the Character type
ABC <Character> charObj = new ABC<Character>('E');
System.out.println("The value of the char is: " + charObj.getObject());
}
} 

Output:

 The value of the integer is: 17
The value of the string is: Tutorial & Example
The value of the float is: 9.9
The value of the char is: E 

Explanation:The above-written code showshow easy it is to create instances of different datatypes with the help of the user-defined Generic class ABC.

Let’s see another example of Java generic.

FileName: GenericsExample1.java

 // A Java program that shows the working of the user-defined
// Generic class having multiple parameters
// We use <> to specify Parameter type
class ABC<U, T>
{
// A reference of type U
U uObj;
// A reference of type T
T tObj;
// constructor of the class ABC
ABC(U obj1, T obj2)
{
    this.uObj = obj1;
    this.tObj = obj2;
}
// For printing the objects of types T and U
public void print()
{
    System.out.println(uObj);
    System.out.println(tObj);
}
// a method for returning object of type T
public T getTObj()  { return tObj; }
// a method for returning object of type U
public U getUObj()  { return uObj; }
}
// Driver class
public class GenericsExample1
{
// main method
public static void main (String argvs[])
{
// An instance of the Integer, Character type
ABC <Integer, Character> intCharObj = new ABC<Integer, Character>(10, 'Q');
System.out.println("The value of the integer is: " + intCharObj.getUObj());
System.out.println("The value of the character is: " + intCharObj.getTObj());
// An instance of the String, Float type
ABC <String, Float> strFloatObj = new ABC<String, Float>("Tutorial & Example", 78.90f);
System.out.println("The value of the string is: " + strFloatObj.getUObj());
System.out.println("The value of the float is: " + strFloatObj.getTObj());
// An instance of the Character, Float type
ABC <Character, Float> charFloatObj = new ABC<Character, Float>('V', 7.09f);
System.out.println("The value of the character is: " + charFloatObj.getUObj());
System.out.println("The value of the float is: " + charFloatObj.getTObj());
}
} 

Output:

 The value of the integer is: 10
The value of the character is: Q
The value of the string is: Tutorial & Example
The value of the float is: 78.9
The value of the character is: V
The value of the float is: 7.09 

Generics Methods in Java

Similar to Generic Classes,Java allows us to create generics methods. Observe the following program.

FileName: GenericsExample2.java

 // A Simple Java program to show working of user defined
// Generic functions
public class GenericExample2
{
// A Generic method example
public <T> void display (T ele)
{
    System.out.println(ele.getClass().getName() + " = " + ele);
}
// main mehtod
public static void main(String argvs[])
{
    // creating an instance of the class GenericExample2
    GenericExample2 obj = new GenericExample2();
    // invoking the generic method with the Integer argument
    obj.display(151);
    // Calling generic method with String argument
    obj.display("Tutorial & Example");
    // Calling generic method with float argument
    obj.display(1.51f);
    // Calling generic method with double argument
    obj.display(1.67);
}
} 

Output:

 java.lang.Integer = 151
java.lang.String = Tutorial & Example
java.lang.Float = 1.51
java.lang.Double = 1.67 

Advantages of Generics in Java

1) Generics ensure type safety:Generics ensure type safety through various ways.  Observe the following code.

FileName: GenericsExample3.java

 // A basic Java program to demonstrates
// the working of the user-defined
// Generic class
// We use <> to specify Parameter type
class ABC<P>
{
               // An object of type P is declared
               P obj;
               ABC(P obj) { this.obj = obj; } // constructor
               public P getObject() { return this.obj; }
}
// Driver class for doing
// the testing of above
public class GenericsExample3
{
// main method
public static void main (String argvs[])
{
               // an instance of the Integer type
               ABC <Integer> intObj = new ABC<Integer>(105);
               System.out.println("The value of the integer is" + intObj.getObject());
               // an instance of the String type
               ABC <String> strObj = new ABC<String>("Tutorial & Example");
               System.out.println("The value of the string is " + strObj.getObject());
               intObj = strObj; // it results in an error
}
} 

Output:

Explanation:Even thoughintObj and strObj are the objects of the same class ABC, they represent the difference in parameter type. Hence, the error occurs, which shows that Generics ensures type safety.

Not only this, but Generics also helps to make errors appear at the compile time. Supposethere is an ArrayList (without Generic) that stores the person’s name, and if someone stores a number by mistake, this mistakeignored by the compiler. Observe the following code.

FileName: GenericsExample4.java

 // A Simple Java program to demonstrate that NOT using
// generics may cause run time exceptions
// importing ArrayList
import java.util.ArrayList;
public class GenericsExample4
{
    // main method
    public static void main(String argvs[])
    {
        // Creating an ArrayList that has not specified any type
        ArrayList personNames = new ArrayList();
        personNames.add("Rahul Dravid");
        personNames.add("Virender Sehwag");
        personNames.add("Sachin Tendulkar");
        personNames.add("Zaheer Khan");
        personNames.add("Virat Kohli");
        personNames.add("Anil Kumble");
        personNames.add(12); // Compiler accepts it without any issue
        // size of the array list
        int size = personNames.size();
        // printing the ArrayList elements
        for(int i = 0; i < size; i++)
        {
            System.out.println(personNames.get(i));
        }
    }
} 

Output:

 Rahul Dravid
Virender Sehwag
Sachin Tendulkar
Zaheer Khan
Virat Kohli
Anil Kumble
12 

Explanation:Till this point, everything seems fine.However, it should not be fine, as 12 should not be entertained in the person’s name list. The above code is potent to throw an exception or error. Supposethe next task is to find the length of strings present in the list, then at that time, we will face issues. Observe the following code.

FileName: GenericsExample5.java

 // A Simple Java program to demonstrate that NOT using
// generics may cause run time exceptions
// importing ArrayList
import java.util.ArrayList;
public class GenericsExample5
{
// main method
public static void main(String argvs[])
{
    // Creating an ArrayList that has no any type specified
    ArrayList personNames = new ArrayList();
     personNames.add("Rahul Dravid");
     personNames.add("Virender Sehwag");
     personNames.add("Sachin Tendulkar");
     personNames.add("Zaheer Khan");
     personNames.add("Virat Kohli");
     personNames.add("Anil Kumble");
     personNames.add(12); // Compiler accepts it without any issue
// size of the array list
    int size = personNames.size();
    // printing the ArrayList elements
    for(int i = 0; i < size; i++)
    {
        System.out.println(personNames.get(i));
    }
    // for storing the length of strings
    int len[] = new int[size];
    // loop for finding the string length
    for(int i = 0; i < size; i++)
    {
        len[i] = ((String)personNames.get(i)).length();
    }
}
} 

Output:

Explanation:We observe thatthe program did not get terminated normallybecause of the presence of number 12 in the list of strings. It raised the ClassCastException. In order to avoid such exceptions, it is better to catch such issues during the compile time. In fact, it is always better to address as many issues as one can during compile-time. It is because compile-time issues are much easier to handle as compared to runtime issues, such as exceptions. To fix this issue during compile time, one has to use generics. The following program shows the same.

FileName: GenericsExample6.java

 // A Simple Java program to demonstrate that using
// generics,one can catch issues during the compile time
// importing ArrayList
import java.util.ArrayList;
public class GenericExample6
{
// main method
public static void main(String argvs[])
{
    // Creating an ArrayList of type specified as String
    ArrayList<String> personNames = new ArrayList<String>();
     personNames.add("Rahul Dravid");
     personNames.add("Virender Sehwag");
     personNames.add("Sachin Tendulkar");
     personNames.add("Zaheer Khan");
     personNames.add("Virat Kohli");
     personNames.add("Anil Kumble");
     personNames.add(12); // now, the compiler will not allow
    // size of the array list
    int size = personNames.size();
    // printing the ArrayList elements
    for(int i = 0; i < size; i++)
    {
        System.out.println(personNames.get(i));
    }
    // for storing the length of strings
    int len[] = new int[size];
    // loop for finding the string length
    for(int i = 0; i < size; i++)
    {
        len[i] = ((String)personNames.get(i)).length();
    }
}
} 

Output:

Explanation:Now, we get the compilation error, as the compiler is not allowing 12 in the String array list, which is better as we do not have to wait for the last loop to find the length of the string to get the exception. Also, the ArrayList is ensuring type safety as it is not allowing the number 12 in its list. Thus, type safety is also ensured.

2) In Generics, typecasting is not required: Generics allows us to specify the parameter type. Therefore, only elements of that type are entertained in the list, not the other one; hence typecasting is not required. In the absence of generics, one has to do the type casting explicitly. Consider the following programs.

FileName: GenericsExample7.java

 // A Simple Java program to demonstrate that type casting
// is required when generics is not used.
// importing ArrayList
import java.util.ArrayList;
public class GenericsExample7
{
    // main method
    public static void main(String argvs[])
    {
        // Creating an ArrayList that has not specified any type
        ArrayList personNames = new ArrayList();
        personNames.add("Rahul Dravid");
        personNames.add("Virender Sehwag");
        personNames.add("Sachin Tendulkar");
        personNames.add("Zaheer Khan");
        personNames.add("Virat Kohli");
        personNames.add("Anil Kumble");
        // size of the array list
        int size = personNames.size();
        // printing the ArrayList elements
        for(int i = 0; i < size; i++)
        {
             // typecasting into string
             String name = (String)personNames.get(i);
             System.out.println(name);
        }
    }
} 

Output:

 Rahul Dravid
Virender Sehwag
Sachin Tendulkar
Zaheer Khan
Virat Kohli
Anil Kumble 

FileName: GenericsExample8.java

 // A Simple Java program to demonstrate that type casting
// is not required when generics is used.
// importing ArrayList
import java.util.ArrayList;
public class GenericsExample8
{
    // main method
    public static void main(String argvs[])
    {
        // Creating an ArrayList that has not specified any type
        ArrayList<String> personNames = new ArrayList<String>();
        personNames.add("Rahul Dravid");
        personNames.add("Virender Sehwag");
        personNames.add("Sachin Tendulkar");
        personNames.add("Zaheer Khan");
        personNames.add("Virat Kohli");
        personNames.add("Anil Kumble");
        // size of the array list
        int size = personNames.size();
        // printing the ArrayList elements
        for(int i = 0; i < size; i++)
        {
             // type casting not required!
             String name = personNames.get(i);
             System.out.println(name);
        }
    }
} 

Output:

 Rahul Dravid
Virender Sehwag
Sachin Tendulkar
Zaheer Khan
Virat Kohli
Anil Kumble 

3) Reusability of Code:By creating a generic class or method, one can use different parameter types on the same generic method. Thus, writing code explicitly for different types is not required. The topmost example of in this section shows the same.


Related Topics

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.