Java Reference
In-Depth Information
Solution
Ask the collection if it contains an object of the given value.
Discussion
If you have created the contents of a collection, you probably know what is in it and what is
not. But if the collection is prepared by another part of a large application, or even if you've
just been putting objects into it and now need to find out if a given value was found, this re-
cipe's for you. There is quite a variety of methods, depending on which collection class you
have. The methods in Table 7-4 can be used.
Table 7-4. Finding objects in a collection
Method(s)
Meaning
Implementing classes
Fairly fast search
Arrays , Collections
binarySearch()
Search
ArrayList , HashSet , Hashtable , LinkList ,
Properties , Vector
contains( )
containsKey( ) , con-
tainsValue( )
Checks if the collection contains the object
as a Key or as a Value
HashMap , Hashtable , Properties , TreeMap
Returns location where object is found
ArrayList , LinkedList , List , Stack , Vect-
or
indexOf( )
Search
search( )
Stack
The methods whose names start with contains will use a linear search if the collection is a
collection ( List , Set ), but will be quite fast if the collection is hashed ( HashSet , HashMap ).
So you do have to know what implementation is being used to think about performance, par-
ticularly when the collection is (or is likely to grow) large.
The next example plays a little game of “find the hidden number” (or “needle in a hay-
stack”): the numbers to look through are stored in an array. As games go, it's fairly pathetic:
the computer plays against itself, so you probably know who's going to win. I wrote it that
way so I would know that the data array contains valid numbers. The interesting part is not
the generation of the random numbers (discussed in Generating Random Numbers ) . The ar-
ray to be used with Arrays.binarySearch() must be in sorted order, but because we just
Search WWH ::




Custom Search