可能重复:
In Java, how can I test if an Array contains a certain value?
我正试图做某种事:
for(String s : myArray)
{
if(s is in newArray) //how do you test this? i want something like
//if(newArray.indexOf(s)!=-1)
{
//do nothing
}
else
{
//add to newArray
}
}
有人可以帮忙吗?
答案 0 :(得分:3)
if(newAray.contains(s))
{
//do nothing
}
else
{
//add to newArray
}
答案 1 :(得分:2)
您无法随意向数组中添加项目,因为数组的大小是固定的。您需要先将数组转换为列表,然后将项目添加到te列表,最后将列表转换回数组:
List<String> tmp = new ArrayList<String>(Arrays.asList(newArray));
for(String s : myArray) {
if(!tmp.contains(s)) {
tmp.add(s);
}
}
newArray = tmp.toArray(new String[tmp.size()]);