[Solved] What is generics, its uses and application? [duplicate]


Generics is used to create “Type safe” collections like List, Map etc. It means that we can add only known/expected types to collections in order to avoid storing different data in one collection. For e.g

//without generics
ArrayList list = new ArrayList();
list.add(new Object());
list.add(new Interger());
list.add(new String());

//with generics 
ArrayList<String> list = new ArrayList<String>();
list.add(new Object()); //compile time error
list.add(new Interger()); //compile time error
list.add(new String()); //ok string its expected

As you can see from above code generics have been introduced to create type safe collections so that we wont get some unexpected type of object from collections at runtime.

Apart from collections we can also apply generics to methods and classes

solved What is generics, its uses and application? [duplicate]