interface Collection
public boolean remove(E e); // not really
public void removeAll(Collection c); // not really
}
但实际上却是:
interface Collection
public boolean remove(Object o);
public void removeAll(Collection c);
}
为什么呢?答案同样是因为向后兼容性。x.remove(o) 的接口表明“如果 o 包含在 x 中,则删除它,否则什么也不做。”如果 x 是一个泛型集合,那么 o 不一定与 x 的类型参数兼容。如果 removeAll() 被泛化为只有类型兼容时才能调用(Collection),那么在泛化之前,合法的代码序列就会变得不合法,比如:
// a collection of Integers
Collection c = new HashSet();
// a collection of Objects
Collection r = new HashSet();
c.removeAll(r);
如果上述片段用直观的方法泛化(将 c 设为 Collection
在泛型之前设计的类可能阻碍了“显然的”泛型化方法。这种情况下就要像上例这样进行折衷,但是如果从头设计新的泛型类,理解 Java 类库中的哪些东西是向后兼容的结果很有意义,这样可以避免不适当的模仿。

