Using ArrayUtills in java code it is possible to remove an element from an java array. Below is the code which removes an element at a particlular index (in the code it is '2', which removes element value equalto '10'.
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class RemoveObjectFromArray{
public static void main(String args[]) {
int[] test = new int[] { 10, 13, 10, 10, 105};
System.out.println("Original Array : size : " + test.length );
System.out.println("Contents : " + Arrays.toString(test));
//let's remove or delete an element from Array using Apache Commons ArrayUtils
test = ArrayUtils.remove(test, 2); //removing element at index 2
//Size of array must be 1 less than original array after deleting an element
System.out.println("Size of array after removing an element : " + test.length);
System.out.println("Content of Array after removing an object : "
+ Arrays.toString(test));
} }
It gives the output as:
run:
Original Array : size : 5
Contents : [10, 13, 10, 10, 105]
Size of array after removing an element : 4
Content of Array after removing an object : [10, 13, 10, 105]
How the code can be amended to get the following output:
run:
Original Array : size : 5
Contents : [10, 13, 10, 10, 105]
Size of array after removing an element : 2
Content of Array after removing an object : [ 13, 105]
Try this code
while (ArrayUtils.contains(test, 10)) {
//let's remove or delete an element from Array using Apache Commons ArrayUtils
test = ArrayUtils.removeElement(test, 10); //removing element with value 10
}
It should solve your problem.
I would use an ArrayList in your case but if you want to stick with your array you can do the following:
int count = 0;
for(int i = 0; i < test.length; i++){
if (test[i] == 10) {
count++;
}
}
int[] newTest = new int[count];
count = 0;
for( int = 0; i < test.length; i++){
if(test[i] != 10){
newTest[count++] = test[i];
}
}
i didn't test it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With