Searching in Collection:

The Collections class and the Arrays class both provide methods that allow you
to search for a specific element. When searching through collections or arrays, the
following rules apply:
■ Searches are performed using the binarySearch() method.
■ Successful searches return the int index of the element being searched.
■ Unsuccessful searches return an int index that represents the insertion point.

■ The collection/array being searched must be sorted before you can search it.
■ If you attempt to search an array or collection that has not already been
sorted, the results of the search will not be predictable.
■ If the collection/array you want to search was sorted in natural order, it must
be searched in natural order. (Usually this is accomplished by NOT sending
a Comparator as an argument to the binarySearch() method.)
■ If the collection/array you want to search was sorted using a Comparator, it
must be searched using the same Comparator, which is passed as the second
argument to the binarySearch() method. Remember that Comparators
cannot be used when searching arrays of primitives.
Searching in Arrays:
import java.util.*;
class demo
public static void main(String[] args){
String [] s = {"one", "two", "three", "four"};
for(String i : s)
{System.out.println(i + " ");}
System.out.println("index is="+Arrays.binarySearch(s,"three"));

No comments:

Post a Comment