×

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits.

1. Type-safety: Suppose, we have accidentally inserted an Integer value to an ArrayList that you intended to use to hold the names of books. The error is thus generated at runtime by the Compiler. The issue arises when we try to get it even if the Compiler permits it.

The Compiler displays the faults at build time rather than run time, thanks to generic. Because the problem is hard to spot during runtime, it saves the programmer’s time. Finding mistakes at build time is usually preferable to doing so at run time.

Let’s see a Java program without using Java generic.

GenericsInJava.java

import java.util.ArrayList;
class GenericsInJava
{ 
public static void main(String[] args) 
{ 
// List of Arrays with no types 
ArrayList ListOfNames = new ArrayList(); 
ListOfNames.add("Abhi"); 
ListOfNames.add(“Keshav"); 
ListOfNames.add(18); // The compiler enables this
String s1 = (String)ListOfNames.get(0); 
String s2 = (String)ListOfNames.get(1); 
// generates a runtime exception
String s3 = (String)ListOfNames.get(2); 
} 
}

Output:

Advantages of Generics in Java

Let’s understand the above program with generic concepts.

GenericsInJava.java

import java.util.ArrayList;
class GenericsInJava
{ 
    public static void main(String[] args) 
    { 
        // ArrayList with string type 
        ArrayList<String> ListOfNames = new ArrayList<String>();  
        ListOfNames.add("Abhi"); 
        ListOfNames.add(“Keshav"); 
        ListOfNames.add(18);  // Compiler doesn't allow this  
        String s1 = (String)ListOfNames.get(0); 
        String s2 = (String)ListOfNames.get(1);  
        String s3 = (String)ListOfNames.get(2); 
    } 
}

Output:

Advantages of Generics in Java

java.lang.Error exception in thread "main" Unsolved compilation issue error The parameters (int) at GenericsInJava.main is not relevant for the function add(int, String) in the type ArrayListString> (GenericsInJava.java:12)

2. Typecasting is not required: We should typecast the data while obtaining the information from the ArrayList, as you can see in the program above. If we are not using a generic ArrayList. The typecast is necessary every time. For programmers, it's a hectic problem.

Since we don't have to cast it each time if we already know the data type list, the generic addresses this problem. It is one of the best benefits of using generics in Java.

3. A generic method, class, and interface can be created to reuse the code. The Collection framework provides a wide variety of generic classes. Depending on the type of data, we can utilize them.

Program.java

import java.util.HashMap;
import java.util.Map;


class Program
{ 
    public static void main(String[] args) 
    {
        // Integer as the key and String as the value in a map
        Map<Integer, String> mapIntString = new HashMap<Integer, String>();
        mapIntString.put(1, "HI");
        mapIntString.put(2, "LEARN");
        
        System.out.println("Map of Value Forms");
        for(Integer key : mapIntString.keySet())
            System.out.println(mapIntString.get(key));
        
        // Map containing Integer as key and Float as Value
        Map<Integer, Float> mapIntFloat = new HashMap<Integer, Float>();
        mapIntFloat.put(1, 1.8f);
        mapIntFloat.put(2, 2.1f);
        
        System.out.println("Map of Value Forms");
        for(Integer key : mapIntFloat.keySet())
            System.out.println(mapIntFloat.get(key));
    } 
}

Output

Advantages of Generics in Java

Generics guarantee compile-time safety, enabling the programmer to identify erroneous types while the code is being compiled.

Java Generics allows programmers to reuse their code for whatever type they want. The sorting of an array of objects may be accomplished by a programmer writing a generic procedure. Using generics, a programmer may apply the same logic to String, Double, and Integer arrays.

The absence of the need for individual typecasting is another benefit of utilizing generics. The programmer defines the starting type, which defers the code's operations.

We can use it to create custom algorithms.

Using generics in Java has several benefits, including the following:

  1. Reusability is the primary benefit of generic medications. The same code may be applied to several data types.
  2. Type safety is another benefit of generic.
  3. Typecasting may be done away with by using generics.
  4. It aids in preventing runtime ClassCastException.

Generics provide type security

Generics only permit holding only one kind of thing: This aids in the early detection of mistakes if a new kind of argument is supplied during compilation.

Generics enable code recycling: For instance, you will be required to build many classes if you wish to construct a class that displays the class of parameterized types such as Integers, Doubles, Strings, or even Characters, but with generics, there would only be one class.

The casting of the particular type is not needed for generics: Since generics offer the parameterized type that references an argument, type casting is unnecessary when using them.

Generics aid in error detection during compilation as opposed to runtime.


Related Topics

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Java Math cos() Method

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

1 minute read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

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

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes 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.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.