Why boolean containsAll(Collection < ?> c); method of collection framework is allowed for every type ?.But boolean addAll(Collection< ?extends E> c); allow for ? extends E.So,i wrote a program for clarification. Here is my program
public class ContainAllTest {
// take ServiceDto
ArrayList<ServiceDto> resultList = new ArrayList<ServiceDto>();
void Test() {
ServiceDto serviceDto = new ServiceDto();
serviceDto.setName("test");
resultList.add(serviceDto);
// another arraylist that takes String
ArrayList<String> resultList1 = new ArrayList<String>();
resultList1.add("test");
// no error, goes for run time.Contain all checking is done for two generic type ServiceDto and String:
resultList.containsAll(resultList1);
// error shown at compile time,as addAll take ServiceDto as generic type but the generic type for resultList1 take String:
resultList.addAll(resultList1);
}
So,my question is when can i get advantage of resultList.containsAll(resultList1); when the generic type is different.In my case String and ServiceDto.Was there some thing wrong replacing boolean containsAll(Collection< ? > c) with boolean containsAll(Collection< ?extends E> c)