Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching an array?

 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
luc comeau
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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++){
if(arr[i].equals(key))
System.out.println("Found "+key+ " at pos: "+i);
}

something along those lines
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic