有四种方法可以删除 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 库
立即学习“Java免费学习笔记(深入)”;
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<ImmutableList<ImmutableList<Integer>>> builder = ImmutableList.builder(); // 遍历每一行并过滤掉要删除的列 for (ImmutableList<Integer> row : ImmutableList.copyOf(arr)) { builder.add(ImmutableList.copyOf(row.subList(0, row.size() - 1))); } ImmutableList<ImmutableList<Integer>> 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]; } } }
以上就是java怎么删除数组中一列数据的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号