Finding an Object in a Collection

Problem

You need to see whether a given collection contains a particular value.

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 recipe’s for you. There is quite a variety of methods, depending on which class of collection you have. The following methods can be used:

Method

Meaning

Implementing classes

binarySearch( )

Fairly fast search

Arrays, Collections

contains( )

Linear search

ArrayList, HashSet, Hashtable, LinkList, Properties, Vector

containsKey( ), containsValue( )

Checks if the collection contains the object as a Key or as a Value

HashMap, Hashtable, Properties, TreeMap

indexOf( )

Returns location where object is found

ArrayList, LinkedList, List, Stack, Vector

search()

Linear search

Stack

This example plays a little game of “find the hidden number” (or “needle in a haystack”); 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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.