【问题标题】:Recreating a HashSet in the ArrayList of HashSets在 HashSet 的 ArrayList 中重新创建一个 HashSet
【发布时间】:2012-08-07 11:59:51
【问题描述】:

我有代码

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>());

允许吗?你知道更快的解决方案吗?谢谢。

【问题讨论】:

    标签: java arraylist hashset


    【解决方案1】:

    list.add(pos, new HashSet&lt;Integer&gt;()); 将转到 add a new set at that position and shift the existing one 到 pos+1。这似乎不是你想要的。

    如果你想用一个新的替换集合,使用set:

    list.set(pos, new HashSet<Integer>()); 
    

    就性能而言,ArrayList#set 以恒定时间运行,因此它是替换列表中现有集合的有效方法。

    【讨论】:

      【解决方案2】:

      如果你想替换一个集合的内容,你可以这样做

      Set<Integer> set = list.get(pos);
      set.clear();
      set.add(99); set.add(98);
      

      因为它重用了集合,所以效率稍高。

      【讨论】:

        【解决方案3】:

        如果你使用guava,你可以更简洁地说:

        List<Set<Integer>> list = Lists.newArrayListWithCapacity(50);
        list.set(17, Sets.newHashSet(99, 88));    
        

        【讨论】:

        • newArrayListWithCapacity 在我看来不是很简洁。
        • 是的,但是当您定义列表并获得更严格的成员集初始化时,您会丢失一半的泛型杂物,所以总的来说我认为这是一个很好的交易。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-23
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 2023-04-10
        • 2012-04-29
        • 1970-01-01
        相关资源
        最近更新 更多