Tags | generics |
Java generics is a feature that allows you to create “parameterized data types”. For example, instead of just declaring a collection that can store any data you can pass it a parameter to allow only the objects of certain data types.
Instead of declaring and instantiating a general collection to store pets like this:
ArrayList pets = new ArrayList();
you can do it with a parameter so it can store only String objects like this:
ArrayList<String> pets = new ArrayList<>();
Generics ensure compile-time safety which allows the programmer to catch the invalid types while compiling the code.
Java Generics helps the programmer to reuse the code for whatever type he/she wishes. For instance, a programmer writes a generic method for sorting an array of objects. Generics allow the programmer to use the same method for Integer arrays, Double arrays, and even String arrays.
Another advantage of using generics is that Individual typecasting isn’t required. The programmer defines the initial type and then lets the code do its job.
It allows us to implement non-generic algorithms.
public static <T> int getPets(T[] list, T item) {}
class DemoClass<T> {}
Please go through this tutorial to give yourself a better chance to understand the topic
https://howtodoinjava.com/java/generics/complete-java-generics-tutorial/
https://www.tutorialspoint.com/java/java_generics.htm
https://howtodoinjava.com/java/generics/complete-java-generics-tutorial/