Thursday, 15 August 2013

Design decision of boolean containsAll(Collection c) vs boolean addAll(Collection

Design decision of boolean containsAll(Collection c) vs boolean
addAll(Collection

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");
resultList.containsAll(resultList1); // no error ,goes for run
time.Contain all checking is done for two generic type ServiceDto
and String
resultList.addAll(resultList1);// error shown at compile time,as
addAll take ServiceDto as generic type but the generic type for
resultList1 take String
}
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)

No comments:

Post a Comment