views:

75

answers:

4

Is there an easy way to check a container if it contains a value, not an object? This is the code I'd like to work:


String[] i = {"One", "Two", "Three"};

if (Arrays.asList(i).contains("One")){
return true;
}

Is there a way to do this or will I have to loop through the array myself?

+2  A: 

That should work fine. A String is an object, so you can use the contains(Object) overload (which is based on equals).

Matthew Flaschen
I guess it makes sense that `contains()` uses `.equals` instead of `==`. I think I'm just over thinking this.
Falmarri
+1  A: 

Have you tried that code? It should work.

Java collections use equals to determine contains equality. Thus if the equals method on an object tests for value (rather than reference) equality, what you want will work.

Strings check to see if their values are the same.

oconnor0
A: 

To repeat everybody else, String is an object, so this will work fine. The contains() method uses Object.equals() to determine whether the given object exists in the list.

Michael Angstadt
+1  A: 
class ContainsTest {
    public static void main(String[] args) {
        String[] i = {"One", "Two", "Three"};
        System.out.println(java.util.Arrays.asList(i).contains("One"));
    }  
}

OUTPUT

 ----jGRASP exec: java ContainsTest

true

 ----jGRASP: operation complete.

I'd say it works.

glowcoder