Java容器.contains问题

发布于 2024-09-10 20:08:52 字数 199 浏览 1 评论 0原文

有没有一种简单的方法来检查容器是否包含值而不是对象?这是我想要工作的代码:


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

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

有没有办法做到这一点,或者我必须自己循环遍历数组?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吖咩 2024-09-17 20:08:52

那应该可以正常工作。 String 是一个对象,因此您可以使用 contains(Object) 重载(基于 equals)。

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

赴月观长安 2024-09-17 20:08:52

你试过那个代码吗?它应该有效。

Java 集合使用equals 来确定contains 相等性。因此,如果对象上的 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.

裂开嘴轻声笑有多痛 2024-09-17 20:08:52
class ContainsTest {
    public static void main(String[] args) {
        String[] i = {"One", "Two", "Three"};
        System.out.println(java.util.Arrays.asList(i).contains("One"));
    }  
}

输出

 ----jGRASP exec: java ContainsTest

true

 ----jGRASP: operation complete.

我想说它有效。

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.

玩套路吗 2024-09-17 20:08:52

重复一下其他人,字符串一个对象,所以这可以正常工作。 contains() 方法使用 Object.equals() 来确定给定对象是否存在于列表中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文