有没有一种方法可以在运行时从数组中删除一个元素?
例如:
int[] num = {8, 1, 4, 0, 5};
Output:
Enter the Index: 0
1, 4, 0, 5
Enter the Index: 3
1, 4, 0
Enter the Index: 1
4, 0;
我知道一旦初始化就无法调整数组的长度,在这种情况下,使用 ArrayList 更为实用。但是,是否有一种只使用数组就能解决这种问题的方法呢?
我已经成功地删除了一个元素并显示了减去1后的数组,方法是创建一个新数组并将原始数组的值复制到其中。但问题在于,下一次迭代中输出仍然可以删除一个元素,但大小不会改变。
具体情况如下:
int[] num = {8, 1, 4, 0, 5};
Output:
Enter the Index: 0
1, 4, 0, 5 // in the first loop it goes as I want it.
Enter the Index: 2
1, 4, 5, 5 // this time array's length is still 4 and just duplicates the last value
Enter the Index: 1
1, 5, 5, 5 // length is still the same and so on.
这是我从数组中删除元素的代码:
public static int[] removeElement(int index, int[] n) {
int end = n.length;
for(int j = index; j < end - 1; j++) {
n[j] = n[j + 1];
}
end--;
int[] newArr = new int[end];
for(int k = 0; k < newArr.length; k++) {
newArr[k] = n[k];
}
displayArray(newArr);
return newArr;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = {8, 1, 4, 0, 5};
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
removeElement(index, num);
}
}
public static void displayArray(int[] n) {
int i = 0;
for(; i < n.length - 1; i++) {
System.out.print(n[i] + ", ");
}
System.out.print(n[i]);
}
有没有什么诀窍可以在数组上实现这个功能?还是我真的必须使用ArrayList
?