The Java Developers Almanac 1.4

 
Webexampledepot.com

   
Home > List of Packages > java.util  [51 examples] > Sorted Collections  [6 examples]

e362. Finding an Element in a Sorted List

    // Create a list with an ordered list of strings
    List sortedList = new LinkedList();
    sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"}));
    
    // Search for the word "cat"
    int index = Collections.binarySearch(sortedList, "cat");    // 2
    
    // Search for a non-existent element
    index = Collections.binarySearch(sortedList, "cow");        // -4
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired; see e363 Inserting an Element into a Sorted List.

 Related Examples
e358. Creating a Sorted Set
e359. Sorting an Array
e360. Finding an Element in a Sorted Array
e361. Inserting an Element into a Sorted Array
e363. Inserting an Element into a Sorted List

See also: Arrays    Bits    Collections    Dates    Hash Tables    Lists    Property Files    Sets    Time    Timers   


© 2002 Addison-Wesley.