Java equivalent of Python 'in' - for set membership test?
You can't do it with a straight array, but you can with a Set<T>
by calling .contains
. If you feel like you will be doing a lot of isItemInSet
calls, consider using Set
s instead of arrays -- you will be much happier.
For example, using a HashSet<T>
makes isItemInSet
an O(1) operation (on average). Set insertion and deletion are also similarly fast. Indeed, a HashSet<T>
in Java is essentially the same as a Python set()
(similar underlying concept and performance characteristics) -- you will see a big improvement in speed with many calls to query, insert or delete on the set.