【发布时间】:2014-05-12 18:48:26
【问题描述】:
我需要在java中做数百万个ArrayList的交集,为此我使用了这个方法:
public static ArrayList<Integer> intersection(ArrayList<Integer> a, ArrayList<Integer> b) {
Set<Integer> aSet = new HashSet<Integer>(a);
Set<Integer> bSet = new HashSet<Integer>(b);
for(Iterator<Integer> it = aSet.iterator(); it.hasNext();) {
if(!bSet.contains(it.next())) it.remove();
}
return new ArrayList<Integer>(aSet);
}
在时间方面它是高性能的但是我有很多内存泄漏,我经常会出现内存不足。如何改进功能以在时间和空间上都表现出色?
更新
输入中给出的数组列表必须保持不变。
【问题讨论】:
-
为什么不使用
removeAll()? -
为什么要从列表开始而不是
Sets?而Set有.retainAll() -
如果您不想自己编写代码,
removeAll()是最佳选择。 -
他想做一个交集,而不是从一个列表中删除所有值到另一个。
retainAll()似乎是一个很好的方法。另外,如果你想经常使用集合,我建议你使用 Guava,有很多有用的方法。例如Sets.intersection(set1, set2) -
如果要进行真正的优化,那就是同时处理多个交叉点。你在什么条件下做交叉口?你只是在数千个数组的列表中与每一对数组相交吗?你知道哪些路口需要提前做好吗?
标签: java performance out-of-memory time-complexity space-complexity