首页 > 解决方案 > 在 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

标签: javaarrays

解决方案


您正在丢弃由返回的新数组removeElement

将循环更改为:

for(int i = 0; i < num.length; i++) {
     System.out.print("Enter the Index: ");
     int index = input.nextInt();
     num = removeElement(index, num);
}

推荐阅读