[英]ArrayList and .add() method in java
I am writing a program that has to read information from file and put them into ArrayList, I think my code is right but Eclipse is saying : The method add(int, String[]) in the type ArrayList<String[]> is not applicable for the arguments (int, String)
about account.add(0, x[0]);
我正在编写一个程序,该程序必须从文件中读取信息并将其放入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]);
The method add(int, String[]) in the type ArrayList<String[]> is not applicable for the arguments (int, String)
account.add(0, x[0]);
in my code. 在我的代码中。
My code: 我的代码:
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]);
}
}
}
This is the signature of the method you're using : 这是您使用的方法的签名:
public void add(int index, E element) { ... }
You have ArrayList<String[]>
, so the method expects an array of Strings as a second param. 您具有ArrayList<String[]>
,因此该方法期望将字符串数组作为第二个参数。 And what you provide is just a String (element from the array). 您提供的只是一个字符串(数组中的元素)。
Try this: 尝试这个:
String x[]=line.split("-");
account.add(0, x); // because x is actually an array
Or you can use it like that: 或者您可以像这样使用它:
account.add(x);
If you still need to put elements from the array into your list like you do here: 如果仍然需要像这里一样将数组中的元素放入列表中,请执行以下操作:
account.add(0, x[0]);
account.add(0, x[1]);
account.add(0, x[2]);
try to change ArrayList<String[]>
to ArrayList<String>
. 尝试将ArrayList<String[]>
更改为ArrayList<String>
。
And just a comment that has nothing to do with your question :) This is a better practice: 只是与您的问题无关的评论:)这是一种更好的做法:
// use interface List in the left part :)
List<String[]> account = new ArrayList<>();
Happy hacking :) 快乐黑客:)
You should to just write account.add(x[0]);
您应该只写account.add(x[0]);
For example: 例如:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("smth");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.