Generics in Java with example
What is generics?
The concepts of generics in Java is pretty similar to templates in C++. Generics allow Integer, String, etc or user-defined types to be passed a parameter to methods, classes, and interfaces.
HashSet, ArrayList, HashMap, etc has implemented generics and we can use them for any type.
Why we need generics?
Java generics has many benefits over the non-generic code. Following are some of the important ones:
- Stronger type checks at compile time
- Elimination of casts
- Enabling programmers to implement generic algorithms
Generic class with example:
A generic class is defined with the following format:
class name<T1, T2, ..., Tn> { /* ... */ }
Generic class
/** * Generic version of the User class. * @param <T> the type of the value */ public class User<T> { // T stands for "Type" private T t; public void User(T t) { this.t = t; } public T get() { return t; } }
Call generic class from main
/** * Main class to call generic class. * @param -- no param */ class Main { public static void main (String[] args) { // Integer type object User <Integer> objInt = new User<Integer>(15); System.out.println(objInt.get()); // String type object User <String> objStr = new User<String>("Joe Smith"); System.out.println(objStr.get()); } }