How to remove element from array in Java with example - Biz Tech

How to remove element from array in Java with example

Listen

In Java, you can remove an element from an array by creating a new array without the element. Here’s an example:

</p>
<p>int[] myArray = {1, 2, 3, 4, 5};</p>
<p>// Find the index of the element to remove<br />
int indexToRemove = 2;</p>
<p>// Create a new array with one less element<br />
int[] newArray = new int[myArray.length - 1];</p>
<p>// Copy the elements from the old array to the new array, skipping the element to remove<br />
for (int i = 0, j = 0; i &lt; myArray.length; i++) {<br />
if (i != indexToRemove) {<br />
newArray[j] = myArray[i];<br />
j++;<br />
}<br />
}</p>
<p>// Print the new array<br />
System.out.println(Arrays.toString(newArray)); // Output: [1, 2, 4, 5]</p>
<p>

In this example, we’ve created an array called myArray with five elements. We’ve then specified the index of the element to remove (2, which corresponds to the third element in the array).

We’ve created a new array called newArray with one less element than the original array. We then use a loop to copy the elements from the old array to the new array, skipping the element to remove. We do this by keeping track of two indexes: i for the old array, and j for the new array. Whenever i is not equal to the index of the element to remove, we copy the element to the new array and increment j.

Finally, we print the new array using the Arrays.toString() method. The output shows that the element at index 2 has been removed from the array.