java - 通用集合

标签 java generics

这是 Java (1.6) 集合接口(interface)的一部分:

public interface Collection<E> extends java.lang.Iterable<E> { 
    /* ... */   
    boolean containsAll(java.util.Collection<?> objects);    
    boolean addAll(java.util.Collection<? extends E> es);    
    boolean removeAll(java.util.Collection<?> objects);    
    boolean retainAll(java.util.Collection<?> objects);
    /* ... */   
}

为什么 addAll<? extends E>同时removeAll<?>

最佳答案

我不知道,我用谷歌搜索。我在这里得到了这个解释:http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html

复制部分:

One element of the generifed Collections API that is often confusing at first is the signatures of containsAll(), removeAll(), and retainAll(). You might expect the signatures for remove() and removeAll() to be:

interface Collection<E> { 
  public boolean remove(E e);  // not really
  public void removeAll(Collection<? extends E> c);  // not really
}

But it is in fact:

interface Collection<E> { 
  public boolean remove(Object o);  
  public void removeAll(Collection<?> c);
}

Why is this? Again, the answer lies in backward compatibility. The interface contract of x.remove(o) means "if o is contained in x, remove it; otherwise, do nothing." If x is a generic collection, o does not have to be type-compatible with the type parameter of x. If removeAll() were generified to only be callable if its argument was type-compatible (Collection<? extends E>), then certain sequences of code that were legal before generics would become illegal, like this one:

// a collection of Integers
Collection c = new HashSet();
// a collection of Objects
Collection r = new HashSet();
c.removeAll(r);

If the above fragment were generified in the obvious way (making c a Collection<Integer> and r a Collection<Object>), then the code above would not compile if the signature of removeAll() required its argument to be a Collection<? extends E>, instead of being a no-op. One of the key goals of generifying the class libraries was to not break or change the semantics of existing code, so remove(), removeAll(), retainAll(), and containsAll() had to be defined with a weaker type constraint than they might have had they been redesigned from scratch for generics.

关于java - 通用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9585317/

相关文章:

java - Java 5 中注释类型的编译时检查有何变化?

c# - 从 Idisposable 实现泛型类时编译时的不同行为?

java - Java 中的方法覆盖和泛型问题

Java 泛型返回 int[] 而不是 Integer[]

java - 如何存储密码?

java - 如何使 Java GUI settext 识别二维数组输入的换行符

java - Android - 激活系统键锁(又名锁屏)

reactjs - FlowType - 推断 React 组件的通用类型

java - 在java中将递归帕斯卡三角形居中?

java - Android:无法读取xml