检查集合是否包含对象,通过引用进行比较 [英] Check if a collection contains an object, comparing by reference

查看:167
本文介绍了检查集合是否包含对象,通过引用进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Collection.contains( )方法检查集合是否包含给定对象,使用 .equals()方法执行比较。



来自Java7 Javadoc:


布尔值包含(对象o)
$ b

如果此集合包含
指定的元素,则返回true。更正式地,当且仅当这个
集合包含至少一个元素e,使得(o == null?
e == null:o.equals(e))时,返回true。


有一个聪明的方法来检查一个集合是否包含一个对象 o o == e )?



当然,我可以遍历集合并进行检查,

ul>
  • 我想要执行此操作,而不用 c>等于() li>
  • 我不想更改集合中的对象和集合本身。



  • strong>编辑:



    尽管我的问题是关于 Collection

    解决方案

    对于集合子接口我们使用Java 8, 集合#stream() 是一个干净的选项:

      collection.stream anyMatch(x-> x == key)


    The Collection.contains() method check if a collection contains a given object, using the .equals() method to perform the comparison.

    From Java7 Javadoc:

    boolean contains(Object o)

    Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

    Is there a smart way to check if a collection contains an object o, but comparing by reference instead (i.e. o==e)?

    Of course I can iterate through the collection and make the check, I'm looking for an existing function which can do that.

    Clarifications:

    • I want to perform this operation regardless the equals() implementation of the object in the collection.
    • I don't want to change the objects in the collection nor the collection itself.

    Edit:

    Even though my question is about a general solution for Collection implementations, specific cases for Collection sub-interfaces would also be appreciated.

    解决方案

    For those of us using Java 8, Collection#stream() is a clean option:

    collection.stream().anyMatch(x -> x == key)
    

    这篇关于检查集合是否包含对象,通过引用进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆