我有代码
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 并创建一个新的,如下所示:
// pos is still here
list.add(pos, new HashSet<Integer>());
允许吗?您知道更快的解决方案吗?谢谢。
最佳答案
list.add(pos, new HashSet<Integer>());
将会add a new set at that position and shift the existing one至pos+1
。这似乎不是你想要的。
如果您想用新的一组替换该组,请使用 set
:
list.set(pos, new HashSet<Integer>());
在性能方面,ArrayList#set
以恒定时间运行,因此它是替换列表中现有集合的有效方法。
关于java - 在 HashSet 的 ArrayList 中重新创建 HashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11845483/