检查集合是否包含对象,通过引用进行比较 [英] Check if a collection contains an object, comparing by reference
问题描述
Collection.contains( )方法检查集合是否包含给定对象,使用 .equals()
方法执行比较。
来自Java7 Javadoc:
布尔值包含(对象o)
$ b如果此集合包含
指定的元素,则返回true。更正式地,当且仅当这个
集合包含至少一个元素e,使得(o == null?
e == null:o.equals(e))时,返回true。
有一个聪明的方法来检查一个集合是否包含一个对象 o
( o == e
)?
当然,我可以遍历集合并进行检查,
ul>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屋!