首页 > 解决方案 > 为什么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;
}

标签: javaeclipse

解决方案


形状是一个ArrayList对象Shape。当您调用时,shapes.add()您需要为方法提供Shape要添加到此列表的类型对象。

所以我不确定如何构造一个新Shape对象,我猜它与你从这个文件中读取的内容有关。如果在构造函数中Shape接受Stringarg...这是猜想但是...

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;
}

推荐阅读