Check if a collection contains an object, comparing by reference

前端 未结 6 1549
猫巷女王i
猫巷女王i 2020-12-29 22:13

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

From Java7 Javadoc

6条回答
  •  借酒劲吻你
    2020-12-29 23:06

    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 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.

提交回复
热议问题