Generics

Generics are used to add more type checking at compile time to reduce errors, generics are the way to tell compiler that a common code will be used on a particular type of objects in context like below

Collection col=new HashSet(); 
Collection colOfEmail=new HashSet<>();

here col is a generic collection which can keep objects of any type but colOfEmail is of type String only and can keep only Strings.
<> is diamond operator to identify data type from context. Like in above HashSet instance is created to keep only the strings, this is introduced in 7 only. Also, in 8 it is supported to calculate type for parameters too from contexxt. Generics can be at class level and at method level too. In method level type of generics are specified between access modifier and return type as below

public static int doSthElse(T t){
     return t.hashCode(); 

public static int doSth(T value){
     return value.intValue(); 
}

Upper and lower bounds can also be specified where final type isnot specified but a class in their hierarchy is defined. extends or ssuper is used to define bounds. extends says any class implementing / extending the given class while super says any class upto Object in the hierarchy of given class.
Multiple bound can alos be defined in comma separated list where class name should come first else compiler gives error. Variable type can be with wildcard but actual instance can not be, it has to be specific. Also, assignment can bedone only of spceific type in generic not the bounded types.

interface payloadList<E,P> extends List{
     void setPayload(int index, P val);
     .
     .
     . 

PayloadList<String,String> ss 
PayloadList<String,Integer> si 
PayloadList<String, Exception> se;
List ls=ss; // valid 
List<? extends Integer> intlist=new ArrayList(); 
List<? extends Number> numList=intlist; // valid

here above Payloadlist instances ss,si,se are of type List and can be stored in List or Collection type of variable.
assignment of intList into numList is ok because both are with wildcard.  When there is a wildcard with super classs as extends in generics, we can store lower type template variale in super type template variable.
Where there is no wildcard and objects are specialized to particular class they can not be stored in same class specialized to super type even if specific class has inheritence relation. As below

List ln=new ArrayList() //invalid because ln is of specialized type Number without wildcard.

There can not be static Generic variables in class as below

public class A{ 
     static T t; 
}  

for more info read here.

Comments