问题描述
方法检查集合是否包含给定对象,使用 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)
这篇关于检查集合是否包含对象,通过引用进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!