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

操作Map内的ArrayList时遭遇cannot find symbol错误求助

解决Map中ArrayList操作的"Symbol not found error"错误

问题原因

你声明的inventories是原始类型的Map,未指定泛型参数。尽管实例化时使用了TreeMap<String, ArrayList<Item>>,但变量类型为原始Map,编译器会将get()方法的返回值视为Object类型。而Object类没有get(int)(ArrayList的元素获取方法)或add()方法,因此触发"找不到符号"的错误。

解决方案

修改Map的变量声明,添加泛型参数String, ArrayList<Item>,让编译器明确键值类型:

Map<String, ArrayList<Item>> inventories = new TreeMap<>();
inventories.put("itms_eqped", new ArrayList<>(6));
// 此时get()返回ArrayList<Item>,可正常调用get()或add()方法
System.out.println(inventories.get("itms_eqped").get(0));

补充说明

  • Java 7及以上版本支持菱形运算符<>,实例化TreeMap和ArrayList时可省略重复的泛型参数,简化代码。
  • 若因特殊需求必须使用原始Map类型,可对get()的返回值做强制类型转换,但这种方式存在类型转换异常风险,且代码可读性差,不推荐使用:
    ((ArrayList<Item>) inventories.get("itms_eqped")).get(0);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:50:08