Finding an Object in a Collection


// finding an object in an ArrayList int index = myArrayList.indexOf(myStringObj); // finding an object by value in a HashMap myHashMap.containsValue(myStringObj); // finding an object by key in a HashMap myHashMap.containsKey(myStringObj);



The examples shown in this phrase illustrate how you can find objects in the most commonly used collectionsthe ArrayList, and the HashMap. Using the indexOf() method of the ArrayList, you are able to find the position in the array where a given object is located. If the object passed into the indexOf() method is not found, a value of -1 is returned. A HashMap indexes items by objects instead of by integer values as an ArrayList does. You can use the containsValue() or containsKey() methods to determine if a HashMap contains the passed in object as either a value or a key in the map. The containsValue() and containsKey() methods will return a boolean value.

Some additional methods for finding objects in collections are the binarySearch() and contains() methods.

The binarySearch() method is a method in the utility classes Arrays and Collections. This method searches an array using the binary search algorithm. Prior to calling the binarySearch() method of the Arrays class, the array must be sorted. If it is not sorted, the results will be undefined. The sorting of the array can be done using the Arrays.sort() method. If an array contains multiple items with the value specified as the search value, there is no guarantee which one will be found. Likewise, the binarySearch() method in the Collections class should only be used on a collection that is sorted into ascending order according to the natural ordering of its elements. This can be done using the Collections.sort() method. As with arrays, using this method on an unsorted collection will yield undefined results. If there are multiple elements equal to the object being searched for, there is no guarantee which one will be found.

If a collection is not already sorted, it is probably better to use the indexOf() method rather than performing the sort() followed by the binarySearch(). The sort() can be an expensive operation depending on your collection.

Here we use the binarySearch() method to search an array of integers:

int[] myInts = new int[]{7, 5, 1, 3, 6, 8, 9, 2}; Arrays.sort(myInts); int index = Arrays.binarySearch(myInts, 6); System.out.println("Value 6 is at index: " + index);


This will result in an output of

The value 6 is at index 4.


The ArrayList class also has a contains() method that can be used to check if a given object is a member of a given ArrayList.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net