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

向ArrayList<ArrayList<Integer>>添加元素遇类型错误,如何在指定行添加元素?

解决向ArrayList<ArrayList>指定行添加元素的类型错误

你遇到的错误根源在于类型不匹配:

incompatible types: int cannot be converted to List

ans是List<List<Integer>>类型,它的每个元素都是一个List<Integer>子列表。你写的ans.add(row, el)是试图直接往外层列表里插入一个int类型的元素,这完全不符合外层列表的元素类型要求,所以编译器报错。

修正方法

要给指定行添加元素,需要先获取该行对应的子列表,再调用子列表的add方法来添加元素。把出错的代码行替换成:

ans.get(row).add(el);

完整修正后的代码

class Solution{
    public List<List<Integer>> solve(int[] nums) 
    {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        HashMap<Integer, Integer> hm = new HashMap<>();
        for(int i = 0; i<nums.length; i++){
            if(hm.containsKey(nums[i])){
                hm.put(nums[i], hm.get(nums[i])+1);
            }
            else{
                hm.put(nums[i], 1);
            }
            if(ans.size()<hm.get(nums[i])){
                ans.add(new ArrayList<Integer>());
            }
            int row = hm.get(nums[i]) - 1;
            int el = nums[i];
            // 修正:先获取对应行的子列表,再添加元素
            ans.get(row).add(el);
        }
        return ans;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 06:17:05