• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java: testing if an element belongs to a set

Carlis

Senior member
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?
 
If you use HashSet then Set.contains() is returned in constant type (as opposed to O(n) on List implementations).
 
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.
 
Back
Top