开发者

Java container .contains question

开发者 https://www.devze.com 2023-01-08 05:16 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号