java - 在 Java 运行时从数组中删除元素
问题描述
有没有办法在运行时从数组中删除元素?
例如:
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;
我知道一旦初始化数组就无法调整其长度,在这种示例问题中,使用 anArrayList
更为实用。但是,有没有办法只使用一个数组来解决这种问题?
我设法通过创建新数组并在其中复制原始数组的值来删除一个元素并显示数组-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
?
解决方案
您正在丢弃由返回的新数组removeElement
。
将循环更改为:
for(int i = 0; i < num.length; i++) {
System.out.print("Enter the Index: ");
int index = input.nextInt();
num = removeElement(index, num);
}
推荐阅读
- bash - 带有条件的 gsutil 文件夹列表
- json - AHK 解析 JSON 数据
- excel - VBA:复制行并转置为列时剩余空间过多
- flutter - Flutter - 如何开始列表中的下一个倒计时
- r - 如何从包含特定字符串的数据框中获取列号?
- google-app-engine - 谷歌云端点服务未在 api 库中列出
- excel - 如何为不同的列/工作表循环 VBA 代码
- javascript - Typescript- 具有动态键和预定义键的对象,但具有不同类型的值(或:具有“其余键”定义的对象)
- python - 在 pandas DataFrame 中的字符串中查找子字符串非常慢
- php - 教义,如果ManyToMany关系,如何将附加值传递给连接表行?