[英]Recreating a HashSet in the ArrayList of HashSets
我有代码
List<HashSet<Integer>> list = new ArrayList<HashSet<Integer>>(50);
pos = 17; // just some index less than 50
list.add(pos, new HashSet<Integer>());
list.get(17).add(99);
list.get(17).add(88);
过了一会儿,我想删除里面有{99,88}的HashSet并创建一个新的HashSet,如下所示:
// pos is still here
list.add(pos, new HashSet<Integer>());
可以吗 您知道更快的解决方案吗? 谢谢。
list.add(pos, new HashSet<Integer>());
将在该位置添加一个新集合,并将现有集合移至pos+1
。 那似乎不是您想要的。
如果要用一个新的集替换该集,请使用set
:
list.set(pos, new HashSet<Integer>());
就性能而言, ArrayList#set
以恒定的时间运行,因此它是替换列表中现有集合的有效方法。
如果要替换集合的内容,可以执行此操作
Set<Integer> set = list.get(pos);
set.clear();
set.add(99); set.add(98);
由于它可以重用集合,因此效率更高。
而且,如果您使用番石榴 ,则可以更简洁地说:
List<Set<Integer>> list = Lists.newArrayListWithCapacity(50);
list.set(17, Sets.newHashSet(99, 88));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.