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.
Post History
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 ...
Answer
#1: Initial revision
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. ```java // 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`](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html) does underneath for its `remove(int)` method. Should you be interested in removing and adding elements often, consider using an `ArrayList` instead.