我是JAVA和编程的初学者,所以请耐心等待,因为我可能不会使用正确的术语来正确描述我的疑问。尽管如此,我会尽力而为。所以,我有这个 ArrayList,我将使用它正则表达式,在逗号上拆分它。我真的需要一些帮助来解决这个问题,即使我必须改变我做这个过程的方式。保持这种状态并不重要,对我来说最重要的是最终结果。谢谢。
String temp;
String temp2;
ArrayList <String> tempsplit = new ArrayList<String> ();
ArrayList <String> dominios = new ArrayList<String> (); {
for (int h = 0; h < 191; h++){
temp = features.get(h);
**temp2.add(temp.split(","));
tempsplit.add(temp.split(","));**
//in these last couple lines I get the error "The method add(String) in the type ArrayList<String> is not applicable for the arguments (String[])"
for(int oi = 0; oi < tempsplit.size(); oi++){
for (int t = 0; t < dominios.size() ; t++){
int conf = 0;
if (tempsplit.get(oi) == dominios.get(t)){
conf = 0;
}
else{ conf = 1;
}
if (conf == 1){
dominios.add (tempsplit.get(oi));
}
}
}
Collections.addAll(temp2, temp.split(","));
这将使用帮助类集合按项目添加String[]
。
temp.split(",")
返回一个String[]
。
List<String>.add
将String
作为参数,而不是字符串数组。
但是您可以使用 Collections.addAll
,它将数组作为第二个参数:
Collections.addAll(temp2, temp.split(","));
您也可以使用temp
ArrayList<String>
中的addAll(Collection<String> c)
方法,但随后您必须将数组转换为Collection
:
temp2.addAll(Arrays.asList(temp.split(",")));
有问题的代码本质上是:
ArrayList <String> tempsplit = new ArrayList<String>();
tempsplit.add(temp.split(",")); // compile error
问题是split()
返回一个String[]
,但列表只会接受一个String
。
要修复,请将数组转换为 List 并将其传递给 addAll()
:
tempsplit.addAll(Arrays.asList(temp.split(",")));
或使用实用程序addAll()
方法:
Collections.addAll(tempsplit, temp.split(","));
ArrayList 类型中的方法 add(String) 不适用于参数 (String[])
这意味着你有一个ArrayList<String>
,并且你正在尝试用一个字符串数组(String[]
)而不是单个String
来调用add
方法。该方法需要一个String
,而不是一个数组。
你的 Arraylist 是 String
类型而不是 String[]
并且你正在add()
传递字符串数组string.split()
因为它会给你数组。相反,你可以做
for(String a:temp.split(",")){
tempsplit.add(a);
}