java 即使我们必须遍历数组,如何从java中的数组中删除元素还是可以直接执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6681704/
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
How to remove elements from an array in java even if we have to iterate over array or can we do it directly?
提问by M.K
Possible Duplicates:
How do I remove objects from an Array in java?
Removing an element from an Array (Java)
listOfNames = new String [] {"1","2","3","4"}; //
String [] l = new String [listOfNames.length-1];
for(int i=0; i<listOfNames.length-1; i++) //removing the first element
l[i] = listOfNames[i+1];
// can this work , Is there a better way ? to remove certain elements from an array in this case the first one .
// 这能行吗,有没有更好的方法?在这种情况下从数组中删除某些元素是第一个。
回答by Stephan
Without a for
loop :
没有for
循环:
String[] array = new String[]{"12","23","34"};
java.util.List<String> list = new ArrayList<String>(Arrays.asList(array));
list.remove(0);
String[] new_array = list.toArray(new String[0]);
Tip
If you can, stick with List
, you'll have more flexibility.
提示
如果可以,请坚持使用List
,您将拥有更大的灵活性。
回答by sgokhales
String[] listOfNames = new String [] {"1","2","3","4"};
List<String> list = new ArrayList<String>(Arrays.asList(listOfNames));
list.remove(0);
String[] array = list.toArray(array);