2. Deleting an Array Element by Its Value
Sometimes, you might need to remove an element from an array based on its value rather than its position. This method requires searching for the value first and then removing it using a similar shifting technique as described previously. Here’s how you can do it effectively.
Detailed Steps
- Find the Value: Loop through the array to find the first occurrence of the target value. Note the index where this value is found.
- Shift Elements to Remove the Value: Once the target value is found, shift all subsequent elements one position to the left, starting from this index.
- Handle the Last Element: Since the size of the array cannot be reduced dynamically, you can set the last element to a default value, such as null or 0, depending on the array type.
Example Code
Here is a code example that demonstrates how to delete an element by its value:
Java
public class ArrayValueRemovalExample {
public static void main(String[] args) {
int[] originalArray = {7, 8, 9, 10, 9}; // Initial array
int valueToRemove = 9; // Value to remove
// Finding the index of the first occurrence of the value to remove
int indexToRemove = -1;
for (int i = 0; i < originalArray.length; i++) {
if (originalArray[i] == valueToRemove) {
indexToRemove = i;
break;
}
}
// If the value is found, shift subsequent elements left
if (indexToRemove != -1) {
for (int i = indexToRemove; i < originalArray.length - 1; i++) {
originalArray[i] = originalArray[i + 1];
}
originalArray[originalArray.length - 1] = 0; // Setting last element to default value
}
// Display the modified array
for (int value : originalArray) {
System.out.print(value + " ");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
7 8 10 9 0
This code locates the first occurrence of the value 9 and removes it by shifting the subsequent values. It is particularly useful when you know the value to be removed but not its position.
3. Deleting an Element by Its Value When the Array Contains Duplicates
When working with arrays that contain duplicate values, removing an element based on its value can be a bit more complex, especially if you need to remove all occurrences of that value. This method ensures that every duplicate value is removed effectively.
Detailed Steps
- Identify All Occurrences: Iterate through the array and mark the indices where the target value occurs.
- Shift Elements: For each marked index, shift the subsequent elements to the left. This might require adjusting the array multiple times depending on the number of duplicates.
- Adjust the Array Size: Set the end elements of the array to a default value if you are not resizing the array, to reflect the removal of duplicates.
Example Code
Here’s how you can implement the removal of all duplicates of a specific value in an array:
Java
public class DuplicateValueRemoval {
public static void main(String[] args) {
int[] originalArray = {11, 12, 11, 13, 11}; // Initial array with duplicates
int valueToRemove = 11; // Value to remove
// We need to find out how many times the value occurs
int count = 0;
for (int value : originalArray) {
if (value != valueToRemove) {
originalArray[count++] = value;
}
}
// Set the remaining elements to a default value
while (count < originalArray.length) {
originalArray[count++] = 0; // Assuming 0 is the default value
}
// Display the modified array
for (int value : originalArray) {
System.out.print(value + " ");
}
}
}

You can also try this code with Online Java Compiler
Run Code
In this example, the array initially contains three occurrences of the value 11. The program loops through the array, copying over only those values that are not 11 to the beginning of the array. This effectively removes all duplicates and fills the end of the array with 0.
4. Shifting Elements in the Same Array
Shifting elements within an array is a key operation, especially after removing one or more elements. This technique involves moving elements to new positions within the same array without creating a new array. It's useful for maintaining the order of elements and optimizing space usage.
Detailed Steps
- Determine the Shift Start: Identify the point in the array from which you need to start shifting elements. This is usually the index after an element has been removed.
- Execute the Shift: Move each element from the start point to the end of the array one position to the left. This closes the gap created by the removed element.
- Handle the Array's End: The last element of the array will need to be set to a default value since it will be duplicated after the shift.
Example Code
Here is a simple example demonstrating how to shift elements within the same array:
Java
public class ElementShifting {
public static void main(String[] args) {
int[] array = {14, 15, 16, 17, 18}; // Initial array
int indexToRemove = 2; // We remove the element at index 2, which is '16'
// Shifting elements left from the index after the removed element
for (int i = indexToRemove; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
// Setting the last element to a default value
array[array.length - 1] = 0; // Assuming 0 as the default value
// Displaying the modified array
for (int value : array) {
System.out.print(value + " ");
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[22, 23, 24]
In this example, after removing the element '16', each subsequent element is shifted left to fill the gap. The last element is then set to zero to avoid duplication.
5. Deleting Elements from an ArrayList
Working with Java's ArrayList offers more flexibility compared to arrays, particularly when it comes to removing elements. ArrayList automatically adjusts its size when items are added or removed, making it ideal for situations where you need dynamic array management.
Detailed Steps
- Use the remove() Method: ArrayList provides the remove() method, which can be used to remove elements either by their index or by the object itself.
- Handling Duplicates: If the list contains duplicates, remove() will only delete the first occurrence. To remove all occurrences, you can use a loop or stream API.
- Ensure List Integrity: After removing elements, the list automatically compacts its size, so no manual adjustment of capacity is necessary.
Example Code
Here's an example demonstrating how to remove elements from an ArrayList, including handling multiple occurrences of a value:
Java
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListRemoval {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(20, 21, 22, 23, 24, 20));
// Removing a single element by value - removes the first '20'
numbers.remove(Integer.valueOf(20));
// Removing an element by index - removes the element at index 0 (now '21')
numbers.remove(0);
// To remove all occurrences of '20'
numbers.removeAll(Arrays.asList(20));
// Displaying the modified ArrayList
System.out.println(numbers);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
[22, 23, 24]
In this code, we start by removing the first occurrence of 20 and then the element at index 0. To remove all occurrences of 20, we use the removeAll() method with an Arrays.asList() containing the value to be completely eliminated.
Frequently Asked Questions
What happens if I try to remove an element that is not in the array?
If you attempt to remove an element that doesn't exist in the array, your code won't make any changes to the array. However, it's good practice to check if the element exists before trying to remove it to avoid potential errors.
Can I remove elements from an array without creating a new array?
While you can shift elements within the array to overwrite unwanted elements, the size of the array remains unchanged unless you explicitly create a new array with the reduced size.
Is there a difference in performance between using arrays and ArrayLists for removing elements?
Yes, ArrayLists are generally more efficient for operations that involve frequent insertion and deletion because they automatically adjust their size. Arrays, however, are more performant for fixed-size data operations and accessing elements by index.
Conclusion
In this article, we've learned various methods to remove elements from arrays & ArrayLists in Java. We started with basic for loops for simple removals, advanced to handling values directly, tackled duplicates, and shifted elements within arrays. We also discussed the dynamic capabilities of ArrayLists that simplify removals and automatically manage array sizes.