【发布时间】:2013-08-15 07:05:18
【问题描述】:
为什么 boolean containsAll(Collection c);每种类型 ? 都允许使用收集框架的方法。但是 boolean addAll(Collection 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);
}
所以,我的问题是我什么时候可以利用 resultList.containsAll(resultList1);当泛型类型不同时。在我的情况下是 String 和 ServiceDto。用 boolean containsAll(Collection c 替换 boolean containsAll(Collection c) 是否有问题)
【问题讨论】:
-
Equals 和 hashCode 是 Object 中的方法,即 >。当您搜索包含某些内容的集合时,您不希望每次都将其转换为适当的类型。
-
@artbristol:是的,这本质上是同一个问题,但有更好的答案。我会投票将其标记为重复。
-
如果我必须将我的 Collection> 的内容复制到 Collection 以便我可以调用 containsAll()。它本质上等同于接受 Object 类型参数的 equals() 方法。 (好的,通过类型擦除,两个 Collections 都只是 Collection