Head First Java习题中ArrayList方法传参报错问题求助
问题解决方案
报错原因
The method setLocationCells(ArrayList) in the type DotCom is not applicable for the arguments (int[])
该报错为参数类型不匹配导致:DotCom类中定义的setLocationCells()方法要求入参为ArrayList类型,你调用方法时传入的是int[]基本类型数组,Java不支持这两种类型的自动转换。
推荐解决方案(符合《Head First Java》原题设计要求)
把你当前的int数组转换为ArrayList<Integer>后再传入方法,示例代码如下:
// 假设你现有存储位置的int数组为 int[] locs = {2,3,4}; // 转换为ArrayList ArrayList<Integer> locList = new ArrayList<>(); for (int loc : locs) { locList.add(loc); } // 调用方法即可解决报错 dotCom.setLocationCells(locList);
如果使用Java 8及以上版本,可以用流式写法简化转换逻辑:
import java.util.Arrays; import java.util.ArrayList; import java.util.stream.Collectors; // 转换代码 ArrayList<Integer> locList = Arrays.stream(locs) .boxed() .collect(Collectors.toCollection(ArrayList::new));
可选调整方案
如果不需要严格遵循原题的ArrayList设计要求,也可以直接修改DotCom类的方法定义,把入参类型改为int[]:
// 修改前的方法定义参考 public void setLocationCells(ArrayList<Integer> locs) { // 原有方法逻辑 } // 修改后 public void setLocationCells(int[] locs) { // 对应调整方法内部逻辑即可 }
注意事项
- 不要直接用
Arrays.asList(locs)转换int数组,该方法返回的是固定长度的List实现,不是java.util.ArrayList,传入会触发新的类型错误 - ArrayList建议指定泛型类型
ArrayList<Integer>,不要使用无泛型的裸类型,避免后续类型转换异常
内容的提问来源于stack exchange,提问作者woojye
相关产品推荐
相关产品推荐

