Finding an Object in a Collection


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


Ask the collection if it contains an object of the given value.


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:



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


Linear search


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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.