关于java列表的问题删除

List的方法public boolean remove(Object o)List删除一个对象,但不会移动后面的元素。只能使对象值为空。
恕我直言,这是一个不直观的设计选择,因为删除前后列表的大小保持不变。
是否有一种优雅的方法来获取一个包含元素的列表?

谢谢

不,那不是它的作用。 该元素被删除,其后面的所有索引都减少了一个。 是什么让你认为它的行为不同?

根据Java API, 这里有一个List DOES的remove函数移位

删除此列表中指定位置的元素(可选操作)。 将任何后续元素向左移位(从索引中减去一个元素)。 返回从列表中删除的元素。

编辑:

主要课程:

 import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String[] args) { ArrayList x = new ArrayList(); A one = new A("one"); A two = new A("two"); A three = new A("three"); A four = new A("four"); A five = new A("five"); A six = new A("six"); A seven = new A("seven"); A eight = new A("eight"); A nine = new A("nine"); A ten = new A("ten"); x.add(one); x.add(two); x.add(three); x.add(four); x.add(five); x.add(six); x.add(seven); x.add(eight); x.add(nine); x.add(ten); for(A item:x){ System.out.println(item.getStr()); } x.remove(four); Iterator i = x.iterator(); while(i.hasNext()){ A item = i.next(); System.out.println(item.getStr()); } } } 

A级:

 public class A { private String str; public A(String x){ this.str = x; } public String getStr(){ return this.str; } } 

效果很好! 没有空指针exception。 这是应该怎么做的。 第一个For循环是我对Iterator对象所做的替代语法。 实际上,Java会自动将第一个for循环转换为看起来像while循环的东西。

如果你看一下ArrayList的remove实现 ,它使用一个本地方法fastRemove(index),如下所示: –

/ * *私有删除方法,跳过边界检查并且不*返回删除的值。 * /

 private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } 

它确实使用了arraycopy,它certificate了你获得了全新的新鲜对象列表而不是填充之间的空值。 这是certificate吗?

java.util.List的契约意味着调用remove将导致size()递减。 如果您正在专门讨论java.util.ArrayList那么您可能对内部数组没有移动其元素是正确的,但这是一个实现细节,在99%的情况下对您来说无关紧要。 如果它仍然有用,那么你正在尝试针对特定情况进行优化,你应该实现自己的List或者使用像java.util.LinkedList这样的东西。

您的观察结果是错误的,或者您正在使用其他类型的List实现(而不是ArrayList),它不会将元素移动到要删除的元素的右侧。 你能发布你的代码吗?

如果查看JDK8中的java.util.ArrayList源代码,您将看到remove(Object o)方法有效地将要删除的元素右侧的元素复制到从元素索引开始的同一个数组中。被删除。 查看ArrayList 源代码以获取更多信息:

如果您只需要一个数据数组,那么只需调用toArray()