Java中尝试将int[]存入ArrayList<ArrayList<Integer>>时出现错误
解决方法
你遇到的问题核心是类型不匹配:mat[i]是int[](基本类型数组),而ArrayList<ArrayList<Integer>>要求的元素是ArrayList<Integer>(包装类集合),Java无法自动将int[]转换为ArrayList<Integer>,需要手动完成类型转换。
下面提供两种可行的解决方式:
方式一:手动遍历转换
逐个读取数组中的int元素,自动装箱为Integer后添加到新的ArrayList中:
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>(); int[][] mat = new int[row][col]; // 读取输入到二维数组 for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { mat[i][j] = s.nextInt(); } } // 将每一行数组转换为ArrayList<Integer>并添加 for(int i = 0; i < row; i++) { ArrayList<Integer> rowList = new ArrayList<>(); for(int num : mat[i]) { rowList.add(num); // int自动装箱为Integer } al.add(rowList); }
方式二:使用Stream API(Java 8+)
借助Stream的boxed()方法将int转换为Integer,再收集为ArrayList:
import java.util.stream.Collectors; import java.util.Arrays; // ... 读取二维数组的代码不变 ... for(int i = 0; i < row; i++) { ArrayList<Integer> rowList = Arrays.stream(mat[i]) .boxed() // 把int流转换为Integer流 .collect(Collectors.toCollection(ArrayList::new)); al.add(rowList); }
注意:不要直接使用Arrays.asList(mat[i]),因为该方法对于基本类型数组int[],会把整个数组当作单个元素,得到的是List<int[]>,而非List<Integer>,仍然无法匹配ArrayList<ArrayList<Integer>>的元素类型。
内容的提问来源于stack exchange,提问作者saiteja
相关产品推荐
相关产品推荐

