有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从列表中删除第一个“n”元素而不进行迭代

我需要一种从列表中删除项目的有效方法。如果出现某种情况,我需要从列表中删除第一个“n”元素。有人能建议最好的方法吗?请记住:性能是我的一个因素,所以我需要一种比评级更快的方法。谢谢

我正在考虑一种方法,通过这种方法,第n项可以作为列表的开始,这样0-n项就可以被垃圾收集。可能吗


共 (6) 个答案

  1. # 1 楼答案

    您可以使用ArrayList.removeRange(int fromIndex, int toIndex)

    引用documentation

    Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)

  2. # 2 楼答案

    单线解决方案是:

     list.subList(n, m).clear();
    

    从从索引n开始并在索引m - 1处停止的列表中删除m - n元素

  3. # 3 楼答案

    如果性能对您来说是关键,那么我不确定使用ArrayList中的内置函数是一条出路。我怀疑它们的运行速度比O(n)快,遗憾的是Java文档对此一无所知。也许你应该研究一些定制的结构,比如Rope

  4. # 4 楼答案

    如果您经常修改列表,为什么不使用LinkedList类呢

    如果使用ArrayList类,则在删除项时,数组必须始终移动

  5. # 5 楼答案

    Jigar Joshi的答案已经包含了您需要的解决方案。我想添加一些其他内容。我想,在子列表上调用clear()可以处理您的工作。但它可能正在使用 在后台迭代,我不确定。供您使用的示例脚本:

    ArrayList<Integer> list = new ArrayList<Integer>();
    ArrayList<Integer> subList = (ArrayList<Integer>) list.subList(0, 9);
    subList.clear();
    
  6. # 6 楼答案

    创建^{}

    Returns a view of the portion of this list between fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

    检查此方法的实现,并进行一些测试以确定性能