You could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
Answer from Peter Lawrey on Stack OverflowYou could use commons lang's ArrayUtils.
array = ArrayUtils.removeElement(array, element)
commons.apache.org library:Javadocs
Your question isn't very clear. From your own answer, I can tell better what you are trying to do:
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)
Choices I made here:
I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.
Assuming you do not want your array to contain null values, then you would have to make a method that does it. Something like this should suffice:
public char[] remove(int index, char[] arr) {
char[] newArr = new char[arr.length - 1];
if(index < 0 || index > arr.length) {
return arr;
}
int j = 0;
for(int i = 0; i < arr.length; i++) {
if(i == index) {
i++;
}
newArr[j++] = arr[i];
}
return newArr;
}
Then just replace the old array with the result of remove().
If you don't want to use ArrayList, arraycopy is an alternative:
System.arraycopy(words, 0, result, 0, i);
System.arraycopy(words, i+1, result, i, result.length-i);
where i is your index to delete.
Hope I can help.
EDIT: Of course you should initially define the correct array lengths:
char[] result = new char[words.length-1];