在Java中,有什么快速(而且好看)的方法可以从数组中删除一个元素吗?
你不能从基本的Java数组中删除一个元素。请看一下各种集合和ArrayList吧。
看起来不错的解决方案是首先使用List而不是array。
List.remove(index)
如果你*必须使用数组,两次调用System.arraycopy很可能是最快的。
System.arraycopy
Foo[] result = new Foo[source.length - 1]; System.arraycopy(source, 0, result, 0, index); if (source.length != index) { System.arraycopy(source, index + 1, result, index, source.length - index - 1); }
(Arrays.asList也是处理数组的好选择,但它似乎不支持remove。)
Arrays.asList
remove
当然,创建另一个数组 :)
你不能从基本的Java数组中删除一个元素。请看一下各种集合和ArrayList吧。
看起来不错的解决方案是首先使用List而不是array。
如果你*必须使用数组,两次调用
System.arraycopy
很可能是最快的。(
Arrays.asList
也是处理数组的好选择,但它似乎不支持remove
。)当然,创建另一个数组 :)