Generics

 Generics important points missed in durga sir material:


1.Generics is used at compile time only 

  • Jvm didn't know about generics concept.
  • Generics concept is used by compiler to provide type safety
  • After compiling the code, generics syntax is removed and jvm doesn't know about it
  • At compile time following actions were performed
  1. compiler compiles code normally by considering generic syntax
  2. Removes Generic syntax
  3. compile once again resultant code.
Eg:This can be cleary observed by durga sir examples:

For mmore info refer Type Eraser concept

Example 1:

 1.ArrayList l=new ArrayList<String>();
 2.ArrayList l=new ArrayList<Number>();

     In the above example, compiler checks for object reference, we didn't provide any generic type heren new ArrayList<String> is invoked at run time but by this time, generics syntax will be removed.

Example 2:

Class Test{

public void m1(List<String> l){
}
public void m1(List<Integer> l){
}
}

     In the above example we will get compile ime error beacuse, compiler removes generic syntax and once again checks the code, then we have two m1 methods with exact same syntax so we get name clash.

1.Where to use Type parameters and Wild cards:

    • Type parameters are used at claaa level , method level and for constructors only.
    At Class Level:
     
    public class Test<T>{
    }

    At Method Level:

    public class NonGenericClass {
    private T t;
    public <T> void method(T t){
    }
    }

    At Constructor Level:

    public class Test<T>{
    private T t;
    public Test(T t){
    this.t=t;
    }
    }

    • we can use wild cards with method arguments, return type, variable declaratins etc


    Why one cannot add elements to upper bound but can add to lower bound

    prerequisite: Diff betwwen lower and upper bound, click here

    Upper Bound:

    public void addElementsToList(List<? extends Number> list) {
    list.add(not sure what to add);
    }

    • In the above code we are not sure what to add because upper bounder of number class maeans all its sub classes, we have total 8 subclasses, we can add Integer,Double.Long etc, so compiler will confuse what to add. So we will get compile time error.
    • These upper bound wild cards are best suitable for read only operations.
    Lower Bound:

    public void addElementsToList(List<? super Integer> list) {
    list.add(12);
    }
    • In the above code we can add numbers beacuse, as it is lower bounds it accepts current class and its super claases.In the above case it accepts Integer and Number classes, so we we add integers, it will be accepted























     

    Comments