0

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?

Community
  • 1
  • 1
user1516514
  • 95
  • 1
  • 2
  • 4

2 Answers2

3
if(newAray.contains(s))
{
    //do nothing
}
else
{
    //add to newArray
}
Imaky
  • 1,227
  • 1
  • 16
  • 36
  • it isnt working. my compileer says "Cannot invoke Contains(string) on the Array type String[]" – user1516514 Jul 13 '12 at 00:50
  • Sorry, dasblinkenligth has the answer. You need to do this before the for(s : myArray): List tmp = new ArrayList(Arrays.asList(newArray)); – Imaky Jul 13 '12 at 00:57
2

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()]);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Actually, if he's doing what I think he's doing and trying to avoid adding duplicate items, he might want to convert it to an implementation of Set first. Set is a generic interface (much like List, of which LinkedList is an implementation) which does not allow duplicate elements, so you can just call Set's add method on every element of myArray and rest assured that if it is already in the Set, it has not been added twice. – algorowara Jul 13 '12 at 00:52
  • @CosmicComputer Using a set would not be equivalent, because it would not keep duplicates present in the original array, and it would not preserve the insertion order (unless a linked hash set is used). – Sergey Kalinichenko Jul 13 '12 at 00:56
  • I made the assumption that he doesn't want any duplicates in his array and doesn't particularly care about order. Sorry, should have stated that. It was a rough inference from the code snippet. – algorowara Jul 13 '12 at 01:06