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.
Videos
If example is not final then a simple reassignment would work:
example = new String[example.length];
This assumes you need the array to remain the same size. If that's not necessary then create an empty array:
example = new String[0];
If it is final then you could null out all the elements:
Arrays.fill( example, null );
- See: void Arrays#fill(Object[], Object)
- Consider using an
ArrayListor similar collection
example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.
So guys i'm having trouble finding a solution for this question. I'm kinda frustrated that i didn't solve this kind of problem during my exam for employment.
Problem: The task is to provide an implementation for the given function. int[] removeElem(int[] array, value), the objective is to find if the array contains the given 'value' inside it. if found then remove the element from the array then return an array with a new size, else return original array.
So far this is what i got:
public static void main(String[] args) {
int[] myArray = {5,6,9,4};
int[] newArray = removeElem(myArray,9);
for(int i=0;i<newArray.length;i++){
System.out.print(newArray[i] + " ");
}
}
public static int[] removeElem(int[] array, int value){
int[] tempArray = array;
int newArrayLength = 0;
int[] newArray;
for(int index=0;index < tempArray.length; index++){
if(tempArray[index] == value){
tempArray[index] = -1;
newArrayLength++;
}
}
newArray = new int[tempArray.length - newArrayLength];
for(int index=0;index < newArray.length; index++){
if(tempArray[index] != -1){
newArray[index] = tempArray[index];
}
}
return newArray;
}Unfortunately i can't get it right :/
Edit: Thank you! everyone for suggesting different solutions to this problem, I feel like I need to work more on my solutions and such :|.
The Java Collections framework is something that you should browse. There are also some types that aren't array-like (Set and Map) but you will find that you will use them often. There are many different types of collections, and some have advantages over others for certain types of operations.
Classic arrays
First, the thing that isn't in the collections framework. The Array. Not ArrayList, but rather the classic int[]. The advantage of the array is that it closely maps to what memory is. foo[42] is to lookup. Many system level calls that give you a fixed number of items are arrays and they are good to know. "1,2,3".split(",") returns back an array for example.
The problem with arrays is that they aren't that flexible. Adding an element to the end of an array that already is at is maximum capacity means allocating a new, larger array and then doing an System.arraycopy() (javadoc) to copy all the elements from one array to another array in a timely manner.
To remove an element from the list you need to remove it and then walk the remainder of the list to have everything be contagious again. If you want to remove foo[4] from the list, you then assign foo[4] = foo[5] and foo[5] = foo[6] and so on down to the end of the list. Thats if you have to do it by hand. You can also use that System.arraycopy mentioned to do it for you given the right set of arguments. Something like:
System.arraycopy(foo,5,foo,4,foo.length - 4);
I might have that wrong, but thats the general idea. Copying the array back on itself. It should work.
If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.
Lists
As you see, arrays are a bit awkward to work with. You've got do it all by hand. Its good to know, but a pain to practice. There are two lists that are in common use that make this easier for you. For the most part, Lists look like arrays.
List<Integer> foo = ...;
foo.get(4);
foo.remove(5);
You call methods on them, but you are fetching the 4th element via method call instead of via direct access through the array. See that foo.remove(5). Thats it. You're done. You have removed an element from the list and deleted it. Much easier to remember.
ArrayList
The ArrayList is backed by an Array. This means that doing foo.get(4) runs fast, but foo.add(42, foo.size()+1) is likely to be slow because it has to do all of that moving of things around to allocate a new list (yes, I know that the list can be longer than the size, but lets assume that its the same size as its actual list).
Instead of having to remember how to do all the shuffling, you've got nice methods to do your work for you. It doesn't mean that its not done (the work is still done behind the scenes of the interface), but its something that you don't have to worry about.
So, the ArrayList is for:
- fast get (O(1))
- slow remove and insert (O(length))
- slow append when full (O(length))
LinkedList
For some reason, everyone's goto list implementation is the ArrayList. I don't know why. Many times when I'm working with Lists, the LinkedList is the one that is more applicable. You keep adding things to the end. Rarely do you want the nth element. You just want to iterate over them.
This is what the LinkedList is good for. It does fast remove and append and its iterator is just as fast as the ArrayList. Its just if you want foo.get(400) its going to be a bit slower than the ArrayList implement.
The LinkedList is also a Deque too, but people forget about that. That lets you access the LinkedList as a double ended queue (nice for implementing a Stack or Queue).
So, if you are just appending and iterating, the LinkedList is for you.
- Get is slowish (O(index))
- Fast append (O(1))
- Remove and insert is slowish (O(index))
Note that the O(index) there is a bit of an award bit. It will index depending on which way is faster to get there (from the end or start). So if the LinkedList is 100 long, and you get(10), it starts from the start. If you ask for get(90), it starts from the end. So get(index) is never more than get(length/2), but thats all just factors that don't matter when looking at Big O.
If you must really do this using an array, then you will need to:
copy all elements of the array after the element being deleted down by one position to cover the removed element.
resize your array to be smaller by one element.
Copying elements down by one position can be done either by writing a loop yourself, or by invoking System.arraycopy( src, srcPos, dest, destPos, length).
Resizing the array can be done like this: myArray = Arrays.copyOf( myArray, newCapacity ).
That having been said, if you have any need to manipulate the length of the array, then definitely go with ArrayList instead of using arrays. This wheel has already been invented.