Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on How do I remove an element from a Java array?
Parent
How do I remove an element from a Java array?
One way to remove element from array is to replace element with zero. Below is a rough snippet I am sharing:
int N = sc.nextInt();
int pos = sc.nextInt();
int A[] = new int[N];
if(pos == i) {
A[i]=0;
}
But the problem is that size of the array remains the same still. You have only replaced the element with zero.
What extra steps we need to perform along with this?
Post
Arrays in Java are created with a fixed length, which cannot be changed in its lifetime. The only way to really change the length of the array is to create a new array with the intended length and copy the values over to the new one.
However, given the cost of doing this, there is often no interest in reallocating the array just to remove an element. It is more common to shift all elements after the one to be removed to the left, and to keep track of the effective length of an array separately, thus being able to exclude the trailing elements.
// remove the element of the array at index i
int i = 0;
for (int j = i; j < N - 1; j++) {
A[j] = A[j + 1];
}
N -= 1;
This is roughly what java.util.ArrayList
does underneath for its remove(int)
method. Should you be interested in removing and adding elements often, consider using an ArrayList
instead.
1 comment thread