boolean containsAll(Collection <?> c)vs boolean addAll(Collection <?extends E> c)的设计决策; 在集合框架中

abi*_*rai 6 java generics wildcard

为什么boolean containsAll(Collection <?> c); 每种类型都允许使用收集框架的方法吗?.但是 boolean addAll(Collection <?extends E> c); 允许?延伸E.所以,我写了一个澄清程序.这是我的计划

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);    
    }
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是我何时才能获得resultList.containsAll(resultList1)的优势; 当泛型类型不同时.在我的情况下String和ServiceDto.Was 使用boolean containsAll(Collection <?extends E> c)替换boolean containsAll(Collection <?> c)有些错误

Bor*_*der 2

这并不是为了提供优势,而是为了节省 CPU 时钟周期。泛型被编译器删除并替换为强制类型转换。

对于addAll方法类型的安全性需要考虑。应该只允许用户将 的一个Collection<E>或某个子类添加ECollection<E>.

如果你查看源代码,AbstractCollection你会看到这个方法:

public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}
Run Code Online (Sandbox Code Playgroud)

编译后它看起来(类似)

public boolean addAll(Collection c) {
    boolean modified = false;
    for (Object e : c)
        if (add((E)e))
            modified = true;
    return modified;
}
Run Code Online (Sandbox Code Playgroud)

即,要添加的集合的每个元素在添加之前都需要从 转换Object为。E

对于containsAll方法来说并不重要。由于该equals方法被定义为equals(Object other)您可以安全地与任何其他方法一起调用它Collection,并且不存在ClassCastExceptions 的风险。通过避免使用泛型,编译器可以避免添加强制转换。

  • 我不认为它与“cpu 滴答声”有任何关系。 (7认同)
  • 选角可能不是免费的,但我认为这与课程的设计没有任何关系。 (4认同)