java - 为什么java在创建方法时不允许我使用方法add()?
问题描述
出现错误“add(Shape)
类型ArrayList<Shape>
中的方法不适用于参数”。
我想将文件中的数据添加到ArrayList
. Shape 是抽象类的名称,而我正在使用的类就是Helper
该类。
对不起,我对编码不太了解。
public static ArrayList<Shape> create(String fileName) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(fileName));
ArrayList<Shape> shapes = new ArrayList<>();
String line = br.readLine();
while(line != null){
shapes.add();
line = br.readLine();
}
br.close();
return shapes;
}
解决方案
形状是一个ArrayList
对象Shape
。当您调用时,shapes.add()
您需要为方法提供Shape
要添加到此列表的类型对象。
所以我不确定如何构造一个新Shape
对象,我猜它与你从这个文件中读取的内容有关。如果在构造函数中Shape
接受String
arg...这是猜想但是...
public static ArrayList<Shape> create(String fileName) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(fileName));
ArrayList<Shape> shapes = new ArrayList<>();
String line = br.readLine();
while(line != null){
shapes.add(new Shape(line)); // create a new shape to add.
line = br.readLine();
}
br.close();
return shapes;
}
希望这可以帮助。
根据您的评论更新:
public static ArrayList<String> create(String fileName) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(fileName));
ArrayList<String> shapes = new ArrayList<>();
String line = br.readLine();
while(line != null){
shapes.add(line); // add String
line = br.readLine();
}
br.close();
return shapes;
}
推荐阅读
- python - 为什么@abstractmethod 装饰器只影响使用常规继承派生的子类?
- mysql - 如何使用从 Squalize 生成的模型获取关联数据?
- java - 在 IntelliJ 中找不到 GsonBuilder 的方法“setLenient”
- azure - 查找 kusto 查询的开始和结束时间(或时间跨度)在 azure log analytics 上运行?
- django - Django REST 和 React 实现模型
- reactjs - React 事件处理程序在没有 bind() 的情况下工作
- spring-mvc - 将 Spring MVC 与 Wildfly 安全域和 Java 安全集成
- java - 如何让 this.name 在值对象构造函数的类定义中工作?
- javascript - 如何在地图函数中合并 React TableCells?
- acumatica - 如何使自定义字段显示超过 2 个小数位