File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Searching an array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Searching an array?" Watch "Searching an array?" New topic

Searching an array?

Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191
How do i search a String array for an element within it. For example, suppose in an array with a list of module codes for an academic course. I then need to search this array for a particular module code. How do i do this.

Moosey knows best
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
You have to loop through the array and check for it manually.

Or you can use the binarySearch method in the Arrays class.

But this will work only if the array is already sorted. Else call Arrays.sort ( ) before calling the binarySearch method.
[ February 07, 2006: Message edited by: Mani Ram ]

Quaerendo Invenietis
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
You may be better of (for many reasons) using a List instead of an array. To find an element in a List, you can use its indexOf method:

There is no emoticon for what I am feeling!
luc comeau
Ranch Hand

Joined: Jan 20, 2005
Posts: 97
could just do the good old fashion for loop, look at each element in the array and compare it to the key you are trying to find in that array.quick example.
say arr is an array of many strings
say key is the string which you are trying to find
for(int i=0;i<arr.length;i++){
System.out.println("Found "+key+ " at pos: "+i);

something along those lines

National Research Council<br />Internet Logic Department
I agree. Here's the link:
subject: Searching an array?
It's not a secret anymore!