Can I remove a specific element from array by mentioning index value?
For example can I remove the character d by giving index value 1?
<
If you need to remove one or multiple elements from array without converting it to List nor creating additional array, you may do it in O(n) not dependent on count of items to remove.
Here, a is initial array, int... r are distinct ordered indices (positions) of elements to remove:
public int removeItems(Object[] a, int... r) {
int shift = 0;
for (int i = 0; i < a.length; i++) {
if (shift < r.length && i == r[shift]) // i-th item needs to be removed
shift++; // increment `shift`
else
a[i - shift] = a[i]; // move i-th item `shift` positions left
}
for (int i = a.length - shift; i < a.length; i++)
a[i] = null; // replace remaining items by nulls
return a.length - shift; // return new "length"
}
Small testing:
Character[] words = {'c','d','f','h','j'};
removeItems(words, 1);
System.out.println(Arrays.asList(words)); // [c, f, h, j, null]