如何在java中删除数组中的元素,即使我们必须迭代数组,还是我们可以直接执行?

时间:2011-07-13 15:46:13

标签: java arrays

  

可能重复:
  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];

//这可以吗,有更好的方法吗?从这个例子中删除数组中的某些元素。

2 个答案:

答案 0 :(得分:2)

没有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]);

提示
  如果可以,坚持使用List,您将拥有更多灵活性

答案 1 :(得分:2)

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);