【问题标题】:Remove an object from an ArrayList without (implicitly) looping through it从 ArrayList 中删除一个对象而不(隐式)循环遍历它
【发布时间】:2016-03-19 10:27:13
【问题描述】:

我正在遍历列表 A 以查找 X。然后,如果找到 X,则将其存储到列表 B。之后,我想从列表 A 中删除 X。因为速度对我的应用程序来说是一个重要问题,我想从 A 中删除 X 而不是遍历 A。这应该是可能的,因为我已经知道 X 在 A 中的位置(我在第一行找到了它的位置)。我该怎么做?

for(int i = 0; i<n; i++) {
        Object X = methodToGetObjectXFromA();
        B.add(X);
        A.remove(X); // But this part is time consuming, as I unnecessarily loop through A
    }

谢谢!

【问题讨论】:

标签: java loops arraylist


【解决方案1】:

您可以返回其索引,然后按索引删除,而不是从方法中返回对象:

    int idx = methodToGetObjectIndexFromA();
    Object X = A.remove(idx); // But this part is time consuming, as I unnecessarily loop through A
    B.add(X);

但是,请注意,由于数组元素的潜在移动,remove 方法可能仍然很慢。

【讨论】:

    【解决方案2】:

    您可以使用迭代器,如果性能是一个问题,您可以使用 LinkedList 作为要从中删除的列表:

    public static void main(String[] args) {
    
    
        List<Integer> aList = new LinkedList<>();
        List<Integer> bList = new ArrayList<>();
        aList.add(1);
        aList.add(2);
        aList.add(3);
    
        int value;
        Iterator<Integer> iter = aList.iterator();
        while (iter.hasNext()) {
            value = iter.next().intValue();
            if (value == 3) {
                bList.add(value);
                iter.remove();
            }
        }
    
        System.out.println(aList.toString()); //[1, 2]  
        System.out.println(bList.toString()); //[3]
    
    }
    

    【讨论】:

      【解决方案3】:

      如果您将所有要删除的对象存储在第二个集合中,您可以使用ArrayList#removeAll(Collection)

      从此列表中删除包含在 指定的集合。 参数: c 包含要从此列表中删除的元素的集合

      在这种情况下,就这样做

      A.removeAll(B);

      退出循环时。


      加法

      它调用ArrayList#batchRemove,它将使用循环来删除对象,但您不必自己做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-10
        • 2012-03-30
        • 1970-01-01
        • 2020-06-15
        • 1970-01-01
        • 2017-07-16
        • 1970-01-01
        相关资源
        最近更新 更多