You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在main方法中正确传入适配countSort的List<List<Integer>>参数?

解决countSort方法的参数适配问题

你的代码出现编译错误有两个核心原因:

  • 类型不兼容:int[][]是基本类型的二维数组,而countSort要求的参数是List<List<Integer>>(包装类型的嵌套列表),Java不会自动完成这种类型转换。
  • 方法调用错误:countSort是Sorted类的静态方法,你错误地用Arrays.countSort调用,应该直接用Sorted.countSort。

下面提供两种可行的解决方式:

方式一:直接初始化List<List<Integer>>作为输入

直接创建符合参数类型的嵌套列表,无需数组转换,代码更简洁:

public class Sorted {

    public static void countSort(List<List<Integer>> inputData) {
        Map<Integer, List<Integer>> dataAsMap = new HashMap<>();
        for(List<Integer> row : inputData) {
            Integer id = row.get(0); 
            Integer item = row.get(1);
            List<Integer> rowInMap = dataAsMap.get(item);
            if (rowInMap == null) {
                rowInMap = new ArrayList<>();
                dataAsMap.put(item, rowInMap);
            }
       
            rowInMap.add(id);
        }
    }
 
        
    public static void main(String[] args) {
        // 直接初始化符合要求的嵌套列表
        List<List<Integer>> inputList = new ArrayList<>();
        inputList.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
        inputList.add(new ArrayList<>(Arrays.asList(101, 102, 103)));
        // 正确调用本类的静态方法
        Sorted.countSort(inputList);
    }    
}

注:Arrays.asList返回的是固定大小的列表,如果需要后续修改列表元素,建议用new ArrayList<>(Arrays.asList(...))转成可修改的ArrayList。

方式二:将int[][]转换为List<List<Integer>>

如果必须保留int[][]的初始化逻辑,可以手动遍历数组完成类型转换:

public class Sorted {

    public static void countSort(List<List<Integer>> inputData) {
        Map<Integer, List<Integer>> dataAsMap = new HashMap<>();
        for(List<Integer> row : inputData) {
            Integer id = row.get(0); 
            Integer item = row.get(1);
            List<Integer> rowInMap = dataAsMap.get(item);
            if (rowInMap == null) {
                rowInMap = new ArrayList<>();
                dataAsMap.put(item, rowInMap);
            }
       
            rowInMap.add(id);
        }
    }
 
        
    public static void main(String[] args) {
        int[][] newArray = {{1, 2, 3}, {101, 102, 103}};
        // 转换int[][]为List<List<Integer>>
        List<List<Integer>> inputList = new ArrayList<>();
        for (int[] row : newArray) {
            List<Integer> integerRow = new ArrayList<>();
            for (int num : row) {
                integerRow.add(num); // 自动完成int到Integer的装箱
            }
            inputList.add(integerRow);
        }
        // 正确调用方法
        Sorted.countSort(inputList);
    }    
}

内容的提问来源于stack exchange,提问作者user18984687

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:15:36