java怎么删除数组中一列数据

有四种方法可以删除 Java 数组中的一列数据:使用 System.arraycopy() 复制数组的每一行,跳过要删除的列。使用 Guava 库遍历每一行并过滤掉要删除的列。使用 Apache Commons Lang 库直接移除列。手动遍历数组并重新构造一个新数组,排除要删除的列。

如何删除 Java 数组中一列数据

要删除 Java 数组中一列数据,有几种方法:

1. 使用 System.arraycopy()

int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] newArr = new int[arr.length - 1][];

// 复制数组的每一行,跳过要删除的列
for (int i = 0; i < arr.length; i++) {
    newArr[i] = new int[arr[i].length - 1];
    System.arraycopy(arr[i], 0, newArr[i], 0, arr[i].length - 1);
}

2. 使用 Guava 库

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;

int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Builder>> builder = ImmutableList.builder();

// 遍历每一行并过滤掉要删除的列
for (ImmutableList row : ImmutableList.copyOf(arr)) {
    builder.add(ImmutableList.copyOf(row.subList(0, row.size() - 1)));
}

ImmutableList> newArr = builder.build();

3. 使用 Apache Commons Lang 库

import org.apache.commons.lang3.ArrayUtils;

int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] newArr = ArrayUtils.removeColumns(arr, 1);

4. 手动遍历并重构数组

int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] newArr = new int[arr.length][arr[0].length - 1];

// 遍历每一行并创建新数组
for (int i = 0; i < arr.length; i++) {
    for (int j = 0; 

j < newArr[i].length; j++) { if (j < arr[i].length - 1) { newArr[i][j] = arr[i][j]; } } }