I understand the concept of PECS (Producer extends, Consumer super) but still have confusion regarding these notations:
public class PECSTest {
public static void main(String[] args) {
//List<? extends Object> ProducerList = new ArrayList<String>();
//ProducerList.add("1"); // Line 1 :compileTimeError
PECSTest myTest = new PECSTest();
List<String> myList = new ArrayList<String>();
myList.add("abc");
myTest.printMyList(myList);
}
private void printMyList(List<? extends Object> myList) {
// TODO Auto-generated method stub
int i=0;
while(i<myList.size()) {
System.out.println(myList.get(i).getClass()); //Line 2
System.out.println(myList.get(i).charAt(0)); // Line 3
System.out.println(myList.get(i).equals(new String("abc")));
i++;
}
}
}
- Even I have created a list that can accept any object that extends Object class but when i tried to add string it gave compile time error at Line 1. Why So ?
- In the second case when i am passing my List to printMyList method it print each elements class type in String at Line 2 but then at Line 3 why i am not able to call any String class specific methods like charAt. Also why there is no casting required to String.
Also in case of consumer
List<? super Number> myList = new ArrayList<Object>();
myList.add(new Object());// compile time error
Why can't i add Object in myList. Because if we are using super that mean this list can contains objects that are equal and higher than number in heirarchy of Java classes. So new Object() should get added in the list as per that statement.
Thanks.