javaarrayssearchfor-loopelement

Java Test element in an array


Possible Duplicate:
In Java, how can I test if an Array contains a certain value?

I'm trying to do a sort of:

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

can someone please help?


Solution


You cannot add items to arrays at will, because arrays are of fixed size. You need to convert the array to a list first, then add items to te list, and finally convert the list back to array:

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()]);