java中怎么把数组元素消除

消除 Java 数组中元素最简单的方法:直接将需要消除的元素赋值为 null。使用 System.arraycopy() 方法创建新数组,跳过要消除的元素。使用 ArrayList,可动态调整数组大小并删除元素。

如何消除 Java 数组中的元素

直接赋值

最简单的方法是直接将需要消除的元素赋值为 null。例如:

int[] myArray = {1, 2, 3, 4, 5};
myArray[2] = null;

这将消除数组中索引为 2 的元素,将其替换为 null

使用 System.arraycopy() 方法

另一种方法是使用 System.arraycopy() 方法。此方法用于从源数组复制元素到目标数组,可以有效地消除元素。例如:

int[] myArray = {1, 2, 3, 4, 5};
int[] newArray = new int[myArray.length - 1];
System.arraycopy(myArray, 0, newArray, 0, 2);
System.arraycopy(myArray, 3, newArray, 2, newArray.length - 2);

这将创建一个新数组 newArray,其中索引为 2 的元素被消除。

使用 ArrayList

如果您需要在运行时动态调整数组大小,可以使用 ArrayListArrayList 是一个可变长度的数组,允许您添加、删除和插入元素。例如:

ArrayList myList = new ArrayList<>();
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
myList.add(5);
myList.remove(2);

这将在运行时消除索引为 2 的元素。