Wednesday, March 14, 2012

List <?> Vs List <Object>

Are these two are identical ?
1-public void method1(List<?> para)
2-public void method2(List<Object> para)
Answer is NO.<?> is called wildcard in generic.If you see the List<?> without extends and super keyword it's means any type of Object it will accept.List<?> means this method will take any type of List of Object.It could be <Object>,<String>,<MyClass> or any type of List(Any Class :))and same time List<Object> means it will accept only List of Object.even though Object is supper class of the all class in java.it not going to allow user to put String or any class of java .And moreover Polymorphism is work differently for Generic.

Following example could be able to explain .:)



package model;

import java.util.ArrayList;
import java.util.List;

public class Example {

public static void main(String[] args) {
List<Object> objectList = new ArrayList<Object>();
objectList.add("AnyTypeOfObject1");
objectList.add("AnyTypeOfObject2");
objectList.add("AnyTypeOfObject3");
objectList.add("AnyTypeOfObject4");
objectList.add("AnyTypeOfObject5");
List<String> stringList = new ArrayList<String>();
stringList.add("AnyTypeOfString1");
stringList.add("AnyTypeOfString2");
stringList.add("AnyTypeOfString3");
stringList.add("AnyTypeOfString4");
stringList.add("AnyTypeOfString5");
example1(stringList);
example2(objectList);
}

public static void example1(List<?> para) {
System.out.println(para.size());
}

public static void example2(List<Object> para) {
System.out.println(para.size());
}


}