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:
equals()
implementation of the object in the collection.Edit:
Even though my question is about a general solution for Collection
implementations, specific cases for Collection
sub-interfaces would also be appreciated.
contains() method check if a collection contains a given object, using the . equals() method to perform the comparison. 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 ?
The contains(value) method of Properties class is used to check if this Properties object contains any mapping of this value for any key present in it. It takes this value to be compared as a parameter and returns a boolean value as a result. This method is more expensive than the containsKey() method.
The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
The contains(Object element) of java. util. Collection interface is used to check whether the element 'element' exists in this collection.
For those of us using Java 8, Collection#stream()
is a clean option:
collection.stream().anyMatch(x -> x == key)
There is some kind of workaround...
You can use an IdentityHashMap
, with Void
as values (or whatever else -- your choice). You'd then use contains()
on its .keySet()
to check the presence of an element (or .containsKey()
on the map directly).
A second workaround would be to use Guava and Equivalence.identity()
; however your Collection
will have to have elements of type Equivalence.Wrapper<X>
and you'd have to wrap
before checking...
Curiously enough, the JDK does not provide an IdentityHashSet
. This is rather strange considering that the internal implementation of HashSet
uses a HashMap
, so one has to wonder why they didn't do the same for IdentityHashMap
...
Side note: the documentation of Collection
is misleading; not all Collection
implementations rely on .equals()
. See, for instance, SortedSet
or SortedMap
. And, of course, IdentityHashMap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With