Java: testing if an element belongs to a set

Carlis

Senior member
May 19, 2006
237
0
76
I have an element E and want to know if it is equal to any object in the vector V.

Obviously I could make a loop and try each one after another, but is there any built in method that will do this for me? And, more important, would that save computing power?
 

Argo

Lifer
Apr 8, 2000
10,045
0
0
If you use HashSet then Set.contains() is returned in constant type (as opposed to O(n) on List implementations).
 
Sep 29, 2004
18,656
68
91
Anything that extends Set will do the trick. Like Argo said though, you need to understand data structures in order to get a fast implementation.

HashSet and TreeSet are usually fine. Worry about optimizing later once you know there is an issue. LinkedHashSet is a special structure that keeps the keys in the order that you inserted them into the Hashset.

Read this:
<a target=_blank class=ftalternatingbarlinklarge href="https://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html">https://java.sun.com/j2se/1......java/util/Set.html</a>
And pay attention to the "All Known Implementing Classes:" section.


Also, remember to implement Equals() and/or hashCode() in those objects that go in the Set.