有没有办法在运行时从一个数组中删除一个元素?
例如:
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;
Run Code Online (Sandbox Code Playgroud)
我知道一旦初始化你就无法调整数组的长度,并且在这种样本问题中,使用a 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.
Run Code Online (Sandbox Code Playgroud)
这是我从数组中删除元素的代码:
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]);
}
Run Code Online (Sandbox Code Playgroud)
有关如何在阵列上执行此操作的技巧吗?或者我真的必须使用ArrayList?
您正在丢弃返回的新数组removeElement.
将你的循环改为:
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
num = removeElement(index, num);
}
Run Code Online (Sandbox Code Playgroud)