Wednesday, October 30, 2013

Difference between List< ? extends MyParentClass> and List< MyParentClass >



Difference between List< ? extends MyParentClass> and List< MyParentClass >


First look into the following code that is quite self explanatory.
 


  public static void main(String[] args) {
    List<Serializable> serializables = new ArrayList<Serializable>();
    serializables.add(new SomeClass1());
    serializables.add(new SomeClass2());
    process(serializables);
    process2(serializables);//no issues
 
    List<SomeClass1> SomeClassList = new ArrayList<SomeClass1>();
    SomeClassList.add(new SomeClass1());
    SomeClassList.add(new SomeClass1());
    process(SomeClassList);
    process2(SomeClassList);//compile time error in this line
}
 
 
private static void process(List< ? extends Serializable> list){
    Iterator< ? extends Serializable> itr = list.iterator();
    while (itr.hasNext()){
        Serializable s = itr.next();
        System.out.println("process1: " + s.getClass());
    }
}    
 
private static void process2(List<Serializable> list){
    Iterator<Serializable> itr = list.iterator();
    while (itr.hasNext()){
        Serializable s = itr.next();
        System.out.println("process2: " + s.getClass());
    }
}

public class SomeClass1 implements Serializable {
    private static final long serialVersionUID = 1L;
    private int a;
    private int b;
 
/*Getters and setters here*/
}
 
/***Here is my SomeClass2 that I will add it to List***/
import java.io.Serializable;
 
public class SomeClass2 implements Serializable {
    private static final long serialVersionUID = 1L;
    private String s;
 
/*Getters and setters here*/
}


Output is
process1: SomeClass1
process1: SomeClass2
process2: SomeClass1
process2: SomeClass2
process1: SomeClass1
process1: SomeClass1

Extract:
  • List< MyParentClass> aList;
We can add any object that belongs to MyParentClass or below its hierarchy. But if there is any other List say List, we CAN NOT assign it to aList.

  • List< ? extends MyParentClass> bList;
Here if there is any other List say List, we CAN assign it to bList.


Thanks
Manish Kumar Agarwal
Manish.java@outlook.com




 



No comments:

Post a Comment