嗨,我有两个集合的A1,A2,并希望从A1中删除A2的所有元素。
请建议我需要使用哪种类型的集合:
- arraylist
- linkList
- 其他?
有没有库?
感谢所有。阅读您的响应后,我创建了过滤器类似这样的类:
public class Filter {
public <T> Set<T> filter(Set<T> all, Set<T> blocked) {
for (T t : all) {
if(blocked.contains(t)) {
all.remove(t);
}
}
return all;
}
}
使用收集方法Collection.removeAll(Collection<?> c);
好吧,您可以使用 a1.removeAll(a2)
,但是如果您的集合为 HashSet
,则删除将更有效(因为在标签中搜索元素的搜索为 O(1)
,而在 List
s中,则需要O(n)
。)。您是否可以使用HashSet
取决于A1和A2是否可以包含重复元素。
要从集合中删除覆盖equals
和hashCode
的对象(在您的情况下)。那么您不需要库,只需使用removeAll
方法
Collection<SomeType> a1 = new ArrayList<SomeType>();
Collection<SomeType> a2 = new ArrayList<SomeType>();
a1.removeAll(a2);