0

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 .

Community
  • 1
  • 1
M.K
  • 179
  • 1
  • 2
  • 10
  • 1
    Java?.......... please use a short, significant title and state the actual question in the text. – Felix Kling Jul 13 '11 at 15:47
  • If this is not for homework where you need to use arrays, have a look at [Collections](http://download.oracle.com/javase/6/docs/api/java/util/Collections.html), especially [Lists](http://download.oracle.com/javase/6/docs/api/java/util/List.html) – Jacob Jul 13 '11 at 15:48
  • 3
    http://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java – Jacob Jul 13 '11 at 15:50
  • Oh see, I missed `java` in the title because I did not bother to read it (too long). Tag questions appropriately. More users will view it then. – Felix Kling Jul 13 '11 at 15:55
  • Why was this closed? The problem is different than the possible duplicates, as this is trying to remove an element at the end, rather than any element. – Joe0 Jul 13 '11 at 16:37

2 Answers2

2

Without a for loop :

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.

Stephan
  • 41,764
  • 65
  • 238
  • 329
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);
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164