1.11. Finding Items in an Array
Problem
You need to test an array to see if it contains an element. If the array contains the element, you need the index of the matching element.
Solution
Use ArrayUtils.contains()
to see if an array contains a specified
element, and use ArrayUtils.indexOf( ) or
ArrayUtils.lastIndexOf( )
to find the position of a matching element.
The following example demonstrates the use of these three methods:
import org.apache.commons.lang.ArrayUtils;
String[] stringArray = { "Red", "Orange", "Blue", "Brown", "Red" };
boolean containsBlue = ArrayUtils.contains( stringArray, "Blue" );
int indexOfRed = ArrayUtils.indexOf( stringArray, "Red");
int lastIndexOfRed = ArrayUtils.lastIndexOf( string, "Red" );
System.out.println( "Array contains 'Blue'? " + containsBlue );
System.out.println( "Index of 'Red'? " + indexOfRed );
System.out.println( "Last Index of 'Red'? " + lastIndexOfRed );This example locates strings in a string array and produces the following output:
Array contains 'Blue'? true Index of 'Red'? 0 Last Index of 'Red'? 4
Discussion
All three methods work with an object array or any primitive array;
in fact, almost every method defined in ArrayUtils
can be applied to every possible array
type—boolean[], byte[],
char[], double[],
float[], long[],
short[], and Object[]. When
using a primitive array, ArrayUtils compares the
value in question to each element of an array until a match is found.
When using an object array, ArrayUtils calls the
equals( ) method ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access