可能重复:
从数组中删除元素(Java)
如何删除特定的字符串数组值,例如
String[] str_array = {"item1","item2","item3"};
我想要从str_array中删除"item2",请帮忙,我希望输出如下
String[] str_array = {"item1","item3"};
可能重复:
从数组中删除元素(Java)
如何删除特定的字符串数组值,例如
String[] str_array = {"item1","item2","item3"};
我想要从str_array中删除"item2",请帮忙,我希望输出如下
String[] str_array = {"item1","item3"};
我会按照如下方式做:
String[] str_array = {"item1","item2","item3"};
List<String> list = new ArrayList<String>(Arrays.asList(str_array));
list.remove("item2");
str_array = list.toArray(new String[0]);
System.arraycopy
相比,效率较低,特别是在多次使用时。 - FThompsonSystem.arraycopy
是最高效、可扩展的解决方案。但是,如果你需要多次从数组中删除一个元素,你应该使用 List 的实现而不是数组。System.arraycopy
来实现所需的效果。public static Object[] remove(Object[] array, Object element) {
if (array.length > 0) {
int index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(element)) {
index = i;
break;
}
}
if (index >= 0) {
Object[] copy = (Object[]) Array.newInstance(array.getClass()
.getComponentType(), array.length - 1);
if (copy.length > 0) {
System.arraycopy(array, 0, copy, 0, index);
System.arraycopy(array, index + 1, copy, index, copy.length - index);
}
return copy;
}
}
return array;
}
此外,如果你知道你的数组仅包含Comparable
对象,你可以通过使用Arrays.sort
将其排序以提高方法效率,然后再通过修改使用Arrays.binarySearch
而非for循环来查找索引的remove
方法来进一步提高效率。这将把该方法的效率从O(n)提高到O(nlogn)。
Array.newInstance
可能会慢一些,但并不一定如此。在大多数情况下,HotSpot 可以优化它,使其与常规数组实例化一样快。无论哪种方式,您最终都会得到一个更强大和正确的程序。 - gustafc public static String[] removeItemFromArray(String[] input, String item) {
if (input == null) {
return null;
} else if (input.length <= 0) {
return input;
} else {
String[] output = new String[input.length - 1];
int count = 0;
for (String i : input) {
if (!i.equals(item)) {
output[count++] = i;
}
}
return output;
}
}
item
实例,而不仅仅是一个。 - FThompson