Advantages of Generics in Java
Generics deliver a set of practical benefits to Java developers. Working with generic types makes day-to-day coding both simpler and safer, so let's go through the key advantages of generics in Java.
1. Type Safety
Suppose you mean to store a list of book titles in an ArrayList, but you accidentally add an Integer instead of a String. The compiler allows it, and the problem only appears when you read the value back — an error shows up at run time. With generics, the compiler catches such mistakes at compile time rather than run time. Catching errors early saves the programmer time, because tracking down a run-time error is far harder. Spotting problems at compile time is always better than discovering them while the program runs.
Take a look at the version without generics:
import java.util.ArrayList;
class Example {
public static void main(String[] args) {
// ArrayList without any type
ArrayList listOfNames = new ArrayList();
listOfNames.add("Sachin");
listOfNames.add("Rahul");
listOfNames.add(10); // Compiler allows this
String s1 = (String)listOfNames.get(0);
String s2 = (String)listOfNames.get(1);
// Causes Runtime Exception
String s3 = (String)listOfNames.get(2);
}
}Output:
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
at Example.main(Example.java:18)Now the same idea with generics applied:
import java.util.ArrayList;
class Example {
public static void main(String[] args) {
// ArrayList with string type
ArrayList<String> listOfNames = new ArrayList<String>();
listOfNames.add("Sachin");
listOfNames.add("Rahul");
listOfNames.add(10); // Compiler doesn't allow this
String s1 = (String)listOfNames.get(0);
String s2 = (String)listOfNames.get(1);
String s3 = (String)listOfNames.get(2);
}
}Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)
at Example.main(Example.java:12)2. No Typecasting Required
In the example above, when a plain ArrayList is used, every value taken from the list must be typecast. That cast is required each time, which becomes a real burden for programmers. Generics eliminate this problem: once you know the data type the list holds, there is no need to cast on every access. This is one of the strongest advantages of generics in Java.
3. Reusable Generic Methods, Classes and Interfaces
You can write a generic method, class or interface, which lets you reuse the same code. The Collection framework, for example, provides many generic classes you can use with whatever data type you need. Here is a Map example:
import java.util.HashMap;
import java.util.Map;
class Example {
public static void main(String[] args) {
// Map containing Integer as key and String as Value
Map<Integer, String> mapIntString = new HashMap<Integer, String>();
mapIntString.put(1, "Hello");
mapIntString.put(2, "JAVA");
System.out.println("Value form Map");
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.2f);
mapIntFloat.put(2, 2.4f);
System.out.println("Value form Map");
for(Integer key : mapIntFloat.keySet())
System.out.println(mapIntFloat.get(key));
}
}Output:
Value form Map
Hello
JAVA
Value form Map
1.2
2.4Here is a generic method reused with different data types:
public class ExampleWithGeneric {
public static void main(String args[]) {
ExampleWithGeneric obj = new ExampleWithGeneric();
System.out.println("Calling by integer values");
obj.showData(5, 10);
System.out.println("Calling by String values");
obj.showData("Hello", "Java");
System.out.println("Calling by float values");
obj.showData(5.1f, 10.2f);
}
public <T> void showData(T a, T b) {
System.out.println(a);
System.out.println(b);
}
}Keep Exploring JavaGoal
Keep growing your Java skills with these topic guides.
- Java Generics
- JavaGoal Categories
- Data Types in Java
- Java Keywords
- Operators in Java
- What Is a Method in Java
- Control Structures in Java
- Java Control Statements
- If Statement in Java
- Switch Statement in Java
- Loops in Java
- Break Statement in Java
- Continue Statement in Java
- Arrays in Java
- OOPs Concepts in Java
- Class and Object in Java
- Constructor in Java
- Constructor Overloading in Java
- Constructor Chaining in Java
- Inheritance in Java
- Multiple Inheritance in Java
- Polymorphism in Java
- Method Overloading in Java
- Method Overriding in Java
- Abstraction in Java
- Abstract Class in Java
- Interface in Java
- Multiple Inheritance Using Interfaces
- Encapsulation in Java
- Association in Java
- Access Modifiers in Java
- Packages in Java
- Java Import Package
- Enum in Java
- Wrapper Class in Java
- Immutable Class in Java
- Final Keyword in Java
- Final Variable in Java
- Final Method in Java
- Final Class in Java
- Final, Finally and Finalize
- Static Keyword in Java
- Static Variable in Java
- Static Method in Java
- Static Block in Java
- Static Class in Java
- This Keyword in Java
- Super Keyword in Java
- Import in Java
- Nested Classes in Java
- Multithreading in Java
- Thread Life Cycle in Java
- Thread Scheduler in Java
- Java Thread Sleep
- join() Method in Java
- yield() Method in Java
- wait() Method in Java
Join the Conversation
Got a question or an idea about generics? Share it with the JavaGoal community.
Leave a CommentConnect With JavaGoal
Follow on Facebook Chat NowGenerics are a core part of modern Java, and the benefits above show up in everyday code: the compiler catches type mistakes early, casts disappear from your source, and one generic method or class can serve many data types. As you continue with the Collection framework and your own classes, leaning on generics keeps your programs clearer and easier to maintain.
