如何从 Java 中的 ArrayList 中删除除第一个元素之外的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3099527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:27:05  来源:igfitidea点击:

How to remove everything from an ArrayList in Java but the first element

javaarraylist

提问by dfilkovi

I am new to java programming, been programing in php so I'm used to this type of loop:

我是 java 编程的新手,一直在用 php 编程,所以我习惯了这种类型的循环:

int size = mapOverlays.size();
for(int n=1;n<size;n++)
{
    mapOverlays.remove(n);
}

So I want to remove everything but the first item, so why doesn't this work? As I get it, after removal, array keys are rearranged or not?

所以我想删除除第一项之外的所有内容,为什么这不起作用?据我所知,删除后,数组键是否重新排列?

采纳答案by Daniel Engmann

As I get it, after removal, array keys are rearranged or not? Yes, the item which was on position 2 is on position 1 after you removed the item on position 1.

据我所知,删除后,数组键是否重新排列?是的,在您移除位置 1 上的项目后,位置 2 上的项目位于位置 1。

You can try this:

你可以试试这个:

Object obj = mapOverlays.get(0); // remember first item
mapOverlays.clear(); // clear complete list
mapOverlays.add(obj); // add first item

回答by Plamena

Why don't you try backwards?

你为什么不向后尝试?

int size = itemizedOverlay.size();
for(int n=size-1;n>0;n--)
{
    mapOverlays.remove(n);
}

回答by Matthew Flaschen

An ArrayListhas integer indices from 0 to size() - 1. You could do:

AnArrayList具有从 0 到 的整数索引size() - 1。你可以这样做:

int size = mapOverlays.size();
for(int n=1;n<size;n++)
{
    mapOverlays.remove(1);
}

This probably matches what you expect from PHP. It works by continually removing the 1th element, which changes. However, this has poor performance, since the internal array must constantly be shifted down. It is better to use clear()or go in reverse order.

这可能符合您对 PHP 的期望。它的工作原理是不断删除第 1 个改变的元素。然而,这性能很差,因为内部数组必须不断向下移动。最好以clear()相反的顺序使用或使用。

It's too bad removeRangeis protected, as that would be convenient for this type of operation.

太糟糕了removeRange受到保护,因为这对于这种类型的操作来说很方便。

回答by Stephen C

I'm assuming that mapOverlaysholds an ArrayListreference.

我假设它mapOverlays包含一个ArrayList参考。

If mapOverlaysis declared as a Listor ArrayList, then mapOverlays.remove(n)will refer to the remove(int)method that removes the object at a given offset. (So far so good ...)

如果mapOverlays声明为Listor ArrayListmapOverlays.remove(n)则将引用remove(int)在给定偏移量处移除对象的方法。(到现在为止还挺好 ...)

When you remove the nthelement of an array using remove(int), the elements starting at position n + 1and above all get moved down by one. So what you are doing won't actually work in most cases. (In fact, you are likely to remove about half of the elements you want to remove, and then get an IndexOutOfBoundsException.)

当您使用 删除nth数组remove(int)的元素时,从 position 开始的元素n + 1将向下移动 1。所以你正在做的事情在大多数情况下实际上是行不通的。(实际上,您可能会删除大约一半要删除的元素,然后得到一个IndexOutOfBoundsException.)

The best solution is either:

最好的解决方案是:

    for (int i = size - 1; i > 0; i--) {
        mapOverlays.remove(i);
    }

or

或者

    tmp = mapOverlays.remove(0);
    mapOverlays.clear();
    mapOverlays.add(tmp);

(Note that the first solution always removes from the end of the list, avoiding the need to copy elements to fill in the hole left by the removed element. The performance different is significant for a large ArrayList.)

(请注意,第一种解决方案总是从列表的末尾删除,避免需要复制元素来填充被删除元素留下的空洞。对于大型 ArrayList,性能差异是显着的。)

However, if mapOverlaysis declared as a Collection, remove(n)will bind to the remove(<E>)overload which removes the object that matches its argument. Depending on the declared type, this will either give you a compilation error, or the intwill be autoboxed as an Integerand you (probably) won't remove anything. GOTCHA!

但是,如果mapOverlays声明为 a Collectionremove(n)则将绑定到remove(<E>)重载,该重载删除与其参数匹配的对象。根据声明的类型,这将给您一个编译错误,或者int将被自动装箱为 anInteger并且您(可能)不会删除任何内容。 明白了!

回答by Jim

Simple.

简单的。

mapOverlays = Collections.singletonList(mapOverlays.get(0));

回答by Agemen

I think it would be faster to create a new ArrayList with just the first element inside. something like :

我认为创建一个只有第一个元素的新 ArrayList 会更快。就像是 :

E temp = mapOverlays.get(0);
mapOverlays = new ArrayList<E>().add(temp);

回答by fish

If you are using a java.util.Listimplementation instead of array, the size of the array gets smaller everytime you remove something and the n+1item replaces the nitem. This code will eventually result to ArrayIndecOutOfBoundsExceptionwhen nbecomes greated than the last index in the list.

如果您使用的是java.util.List实现而不是数组,则每次删除某些内容并且该n+1项目替换该n项目时,数组的大小都会变小。该代码最终会导致到ArrayIndecOutOfBoundsExceptionn比在列表的最后一个索引变得greated。

Java also has an array type and the size of that one cannot be changed:

Java 也有一个数组类型,它的大小不能改变:

Object[] mapOverlay = //initialize the array here
int size = mapOverlay.length;
for(int n=1;n<size;n++)
{
    mapOverlay[n] = null;
}

I don't know PHP but this sounds like it's close to the behavior you are after. However the List implementations are more flexible and comfortable in use than the arrays.

我不知道 PHP 但这听起来很接近你所追求的行为。然而,List 实现比数组更灵活,使用起来更舒适。

EDIT: Here's a link to the Javadoc of List.remove(int): http://java.sun.com/javase/6/docs/api/java/util/List.html#remove%28int%29

编辑:这里是 Javadoc 的链接List.remove(int)http: //java.sun.com/javase/6/docs/api/java/util/List.html#remove%28int%29

回答by Adam Crume

You could use

你可以用

mapOverlays.subList(1, mapOverlays.size()).clear();

回答by Sonal Patil

int size = mapOverlays.size();
for(int n=0;n<size;n++)
{
    mapOverlays.remove(n);
}

In java, if mapOverlays is list then it start with 0 as a first index.So n=0 in for loop.

在 java 中,如果 mapOverlays 是列表,那么它从 0 作为第一个索引开始。所以在 for 循环中 n=0。

回答by user85421

Use a while loop to remove everything after the first element:

使用 while 循环删除第一个元素之后的所有内容:

while (mapOverlays.size() > 1) {
    mapOverlays.remove(1);
}

EDIT(see comment from Adam Crume)

编辑(见亚当克鲁姆的评论)

If performance is a problem you should use this one

如果性能是一个问题,你应该使用这个

while (mapOverlays.size() > 1) {
    mapOverlays.remove(mapOverlays.size()-1);
}

even a bit micro-optimization

甚至有点微优化

int last = mapOverlays.size() - 1;
while (last >= 1) {
    mapOverlays.remove(last);
    last -= 1;
}



If performance is really a problem (and the list has lots of elements), you should use the sublistsolution. It's a bit harder to read but probably the fastest solution if the list instance can not be recreated (referenced elsewhere).



如果性能确实是一个问题(并且列表中有很多元素),您应该使用sublist解决方案。如果无法重新创建列表实例(在其他地方引用),则阅读起来有点困难,但可能是最快的解决方案。