通过引用进行比较

通过引用进行比较

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

问题描述

方法检查集合是否包含给定对象,使用 c>等于() li>

  • 我不想更改集合中的对象和集合本身。



  • strong>编辑:



    尽管我的问题是关于

    解决方案

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

      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:

    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)
    

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

    09-02 11:03