Java container .contains question
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")){
ret开发者_JAVA技巧urn true;
}
Is there a way to do this or will I have to loop through the array myself?
That should work fine. A String is an object, so you can use the contains(Object)
overload (which is based on equals
).
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.
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.
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.
精彩评论