Generics in Java
Generics in Java
in JAVA
Improving Code Reusability and Type Safety
What Are Generics?
• Java Generics is a set of related methods or a set of
similar types.
• Generics allow types Integer, String, or even user-
defined types to be passed as a parameter to classes,
methods, or interfaces.
List<String> list = new ArrayList<>();
• Introduced in Java5
list.add("Hello");
• Ensures type safety String s = list.get(0); // No casting needed
• Code reusability
• Reduces casting
Types of Generics
• Generic Method: Generic Java method takes a parameter and
returns some value after performing a task. It is exactly like a
normal function, however, a generic method has type parameters
that are cited by actual type. This allows the generic method to be
used in a more general way. The compiler takes care of the type of
safety which enables programmers to code easily since they do not
have to perform long, individual type castings.
• Generic Classes: A generic class is implemented exactly like a
non-generic class. The only difference is that it contains a type
parameter section. There can be more than one type of parameter,
separated by a comma. The classes, which accept one or more
parameters, ?are known as parameterized classes or parameterized
types.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()