要删除Java数组中的指定位置元素,你可以使用以下方法:
例如,假设要删除的元素位置为index:
int[] originalArray = {1, 2, 3, 4, 5};
int[] newArray = new int[originalArray.length - 1];
System.arraycopy(originalArray, 0, newArray, 0, index);
System.arraycopy(originalArray, index + 1, newArray, index, originalArray.length - index - 1);
for (int num : newArray) {
System.out.print(num + " ");
}
输出结果为:1 2 4 5
import java.util.ArrayList;
int[] originalArray = {1, 2, 3, 4, 5};
ArrayList<Integer> arrayList = new ArrayList<>();
for (int num : originalArray) {
arrayList.add(num);
}
int index = 2; // 指定要删除的位置
arrayList.remove(index);
int[] newArray = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
newArray[i] = arrayList.get(i);
}
for (int num : newArray) {
System.out.print(num + " ");
}
输出结果为:1 2 4 5