Generics
Generics is a feature in Java that allows you to define classes, interfaces, and methods with type parameters. It ensures type safety, code reusability, and eliminates explicit type casting.
Features
- Generics are mainly used in collections.
- Generics are mainly used to store specific types of objects.
- Generics are always defined inside the angular braces(<>).
Advantages
- Type Safety – Ensures that only a specific type of object is stored.
- No Need for Type Casting – Objects retrieved from a collection do not require explicit typecasting.
- Compile-time Checking – Errors related to type mismatches are caught at compile time, reducing runtime errors.
Example:
package quipoin;
import java.util.ArrayList;
public class DemoGeneric {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("Web_Technology");
// list.add(20); compilation error because of int type.
System.out.println("Storing string type objects using generics!!");
for (String elements : list) {
System.out.println(elements);
}
}
}
Output:
Storing string-type objects using generics!!
Java
Python
Web_Technology
Explanation
In the above example, we are storing specific types of objects i.e. String type, if we are trying to store other type objects compiler throws an error.
Why Use Generics ?
Without generics, we have to use object type collections, requiring explicit typecasting
ArrayList list = new ArrayList(); // No generics (not type-safe)
list.add("Java");
list.add(10); // No restriction, integer is allowed
String s = (String) list.get(1); // Runtime error (ClassCastException)
With generics, such runtime issues are avoided.Two Minute Drill
- Generics make Java collections safer, more readable, and eliminate the need for typecasting.
-
They are widely used in collections (ArrayList, HashSet, HashMap, etc.) and other generic classes like Comparable
and Comparator .