[英]Why will java not let me use the method add() when creating a method?
出現錯誤“ ArrayList<Shape>
類型中的方法add(Shape)
不適用於參數”。
我想將文件中的數據添加到ArrayList
。 Shape 是抽象 class 的名稱,我正在使用的 class 是Helper
class。
對不起,我對編碼不太了解。
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;
}
shape 是一個采用Shape
對象的ArrayList
。 當您調用shapes.add()
時,您需要提供帶有Shape
類型的 object 的方法以添加到此列表中。
所以我不確定如何構建一個新的Shape
object 我猜它與你從這個文件中讀取的內容有關。 如果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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.