java中的ArrayList和.add()方法

时间:2018-06-15 11:56:37

标签: java arraylist

我正在编写一个程序,必须从文件中读取信息并将它们放入ArrayList中,我认为我的代码是正确的,但Eclipse在我的代码中说The method add(int, String[]) in the type ArrayList<String[]> is not applicable for the arguments (int, String)关于account.add(0, x[0]);

我的代码:

public static void main(String args[]) {

    ArrayList<String[]> account = new ArrayList<>();
    String line = "";
    try {
        FileReader fr=new FileReader("information.txt");

        Scanner information = new Scanner(fr);
        while (information.hasNext()) {

            // find next line
            line = information.next();

            String x[]=line.split("-");
            account.add(0, x[0]);
            account.add(0, x[1]);
            account.add(0, x[2]);
        }
    }
}

2 个答案:

答案 0 :(得分:4)

这是您正在使用的方法的签名:

public void add(int index, E element) { ... }

你有ArrayList<String[]>,所以该方法需要一个字符串数组作为第二个参数。 而你提供的只是一个String(来自数组的元素)。

试试这个:

String x[]=line.split("-");
account.add(0, x); // because x is actually an array

或者你可以这样使用它:

account.add(x);

如果你仍然需要像在这里一样将数组中的元素放入列表中:

account.add(0, x[0]);
account.add(0, x[1]);
account.add(0, x[2]);

尝试将ArrayList<String[]>更改为ArrayList<String>

只是一个与你的问题无关的评论:) 这是一种更好的做法:

// use interface List in the left part :)
List<String[]> account = new ArrayList<>();

快乐的黑客攻击:)

答案 1 :(得分:0)

你应该写account.add(x[0]); 例如:

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("smth");