在Java中运行时从数组中移除元素

4

有没有一种方法可以在运行时从数组中删除一个元素?

例如:

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


我看到你的数组只包含正数。也许你可以用“-1”替换最后一个数字,这样在显示数组时,你可以遍历数组直到到达值为“-1”。 - Dominique
1
@Eran已完成编辑 - robert
1
@Robert,这是一个建议...最好使用Java集合... - PrabaharanKathiresan
3个回答

7

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

请将您的循环更改为:

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

1

从你的代码来看,你并没有真正地从数组中移除一个元素。实际上,你正在创建一个新的数组,大小比之前的小1,并用旧数组的剩余值填充新数组。

此外,你从旧数组中删除元素的逻辑是错误的。首先,你的旧数组仍然具有相同的大小,你所做的只是将数组中索引位置的元素替换为索引位置+1处的元素。


1
你可以尝试这段代码:

public static int[] removeElement(int index, int[] arr) {
    int length = arr.length - 1;
    int[] res = new int[length];
    for(int i = 0; i < index; i++) {
        res[i] = arr[i];
    }
    for(int i = index; i < length; i++) {
        res[i] = arr[i + 1];
    }
    return res;
}

上面代码片段的想法是将数组复制到一个新的数组中(长度减一),跳过我们想要删除的元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接