How to remove a specific value from an array in Java?
In Java, the length of an array is immutable, meaning that it is not possible to directly remove a value from the array. However, you can simulate a removal operation by setting the value to a specific marker.
For example, suppose there is an integer array called nums. To remove elements with a value of target, you can set that element to a specific marker value, such as -1, to indicate that the value has been deleted. The code example is as follows:
public void removeElement(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
nums[i] = -1; // 将目标值设置为标记值-1
break; // 找到目标值后,结束循环
}
}
}
It is important to note that this method only simulates the deletion operation, the length of the array remains unchanged. If one wants to actually remove elements from the array, they can consider using the ArrayList class, which provides more convenient deletion operations.