2011-07-13 27 views
0

可能重複:
How do I remove objects from an Array in java?
Removing an element from an Array (Java)如何從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]; 

//可以這樣工作,有沒有更好的辦法?在這種情況下從第一個數組中刪除某些元素。

+1

Java?..........請使用一個簡短的重要標題並在文中陳述實際問題。 –

+0

如果這不是您需要使用數組的功課,請查看[Collections](http://download.oracle.com/javase/6/docs/api/java/util/Collections.html),特別是[Lists](http://download.oracle.com/javase/6/docs/api/java/util/List.html) – Jacob

+3

http://stackoverflow.com/questions/112503/how-do-i-remove -object-from-an-array-in-java – Jacob

回答

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,你就會有更多的靈活性

+0

'Arrays.asList()'不支持'remove'(或add)。 –

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); 
相關問題