Java Reference
In-Depth Information
13.1 Searching and Sorting in the Java Class Libraries
To search an ArrayList or LinkedList , you can call its indexOf method. This
method examines each element of the list, looking for a target value. It returns the first
index at which the target value occurs in the list, or -1 if the target doesn't occur.
Imagine a large List containing all the words in a book. The following code could
read a large text file into such a list:
// reads the text of the given file into a list
public static List<String> readBook(String filename)
throws FileNotFoundException {
List<String> words = new ArrayList<String>();
Scanner in = new Scanner(new File(filename));
while (in.hasNext()) {
words.add(in.next());
}
return words;
}
You could use the indexOf method to see whether a given word appears in the
book and, if so, at what index the word appears:
System.out.print("Your word? ");
Scanner console = new Scanner(System.in);
String word = console.nextLine();
// search list for a word using indexOf
List<String> words = readBook("mobydick.txt");
int index = words.indexOf(word);
if (index >= 0) {
System.out.println(word + " is word #" + index);
} else {
System.out.println(word + " is not found.");
}
The indexOf method performs a sequential search, examining each element of
the list in sequence until it finds the one that the user is looking for. If it reaches the
end of the list without finding the requested word, it returns -1 . When it searches a
1,000,000-element list for an element at index 675000, a sequential search would
have to examine all 675,000 elements that came before the desired element.
If you have an array of data instead of a list, there's no prewritten method to
sequentially search the array. You'll have to write the code yourself (as we'll do later
in this chapter) or put the array's elements into a List first and search the List with
indexOf .
 
Search WWH ::




Custom Search