使用Java在运行时从数组中删除元素

时间:2018-12-20 08:36:42

标签: java arrays

是否可以在运行时从数组中删除元素?

例如:

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

3 个答案:

答案 0 :(得分: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位置的元素。

答案 2 :(得分: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;
}

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

相关问题