Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means parameterized types. Using generics, the idea is to allow any data type to be it Integer, String, or any user-defined Datatype and it is possible to create classes that work with different data types.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
Example: Single type parameter
class Solution<T>
{
T data;
public static T getData(){
return data;
}
}
Example: Multiple type parameters
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
Here in this example, we can use the object or instance of this class as many times with different Parameters as T type. If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.
We can write a single generic method declaration that can be called with arguments of different types. Based on the types of arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods
- All generic method declarations have a type parameter section indicated by angle brackets <> that precedes the method's return type.
- Each type parameter section can contain one or more type parameters separated by commas. A type parameter or a type variable is an identifier that specifies a generic type name.
- The type parameters can be used to declare the return type which is known as actual type arguments.
- A generic method's body is declared like that of any non-generic method. The point to be noted is that type parameter can represent only reference types, and not primitive types (like int, double, and char).
Advantages of Java Generics
1. Type-Safety: One can hold only a single type of objects in generics.
2. Type Casting Is Not Required: There is no need to typecast.
Example:
Before Generics
List l= new ArrayList();
l.add("India");
String s = (String) l.get(0); // typecasting
After Generics, typecasting of the object is not required
List<String> l = new ArrayList<String>();
l.add("hello");
String s = l.get(0);
3. Compile -Time Checking: It checks all the errors of datatype related to generics at the time of compile-time so the issue will not occurat the time of runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error
For an instance of Generic class
BaseType <Type> object = new BaseType <Type>();
Note: In parameter Type, we cannot use primitives like int, char, float, etc.
Example:
Java
// Java program to show the
// instance of a generic class
// Generic Classes
// we use <> to specify parameter
// type and we can add any datatype
// like Integer, Double, String,
// Character or any user defined
// Datatype
// Every time when we need to make an
// object of another datatype of this
// generic class , we need not to make
// the whole class of that datatype again
// instead we can simply change the
// parameter/Datatype in braces <>
public class Area<T> {
// T is the Datatype like String,
// Integer of which Parameter type,
// the class Area is of
private T t;
public void add(T t)
{
// this.t specify the t variable inside
// the Area Class whereas the right hand
// side t simply specify the value as the
// parameter of the function add()
this.t = t;
}
public T get() { return t; }
public void getArea() {}
public static void main(String[] args)
{
// Object of generic class Area with parameter Type
// as Integer
Area<Integer> rectangle = new Area<Integer>();
// Object of generic class Area with parameter Type
// as Double
Area<Double> circle = new Area<Double>();
rectangle.add(10);
circle.add(2.5);
System.out.println(rectangle.get());
System.out.println(circle.get());
}
}
Similar Reads
Generics in Java Generics means parameterized types. The idea is to allow a type (like Integer, String, etc., or user-defined types) to be a parameter to methods, classes, and interfaces. Generics in Java allow us to create classes, interfaces, and methods where the type of the data is specified as a parameter. If w
10 min read
Generic Class Hierarchies in Java Generic means parameterized types introduced in java5. These help in creating classes, interfaces, methods, etc. A class or method which works on parameterized type known as "generic class " or "generic method". Generics is a combination of language properties of the definition and use of Generic ty
3 min read
Generic Map In Java Java Arrays store items in an ordered collection and the values can be accessed using the index(an integer). Whereas HashMap stores as a Key/ Value pair. Using HashMap, we can store the items or values and these values can be accessed by indexes/ keys of any type be it Integer, String, Double, Chara
3 min read
Generic Set In Java The Set interface is present in java.util package. It is basically a collection of objects with no duplicate objects that means there can be no two objects in a Set e1 and e2 such that e1.equals(e2) and at most one null element. It is an interface that models the mathematical set. This interface inh
3 min read
Generic For Loop in Java When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we wri
4 min read