Java SE API
Collections.binarySearch(List, key)
Search sorted data. Duplicate matches need not return the earliest index.
Formal Syntax & Structure
java syntaxjava
static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| list | List<? extends Comparable<? super T>> | List sorted by natural ordering. |
| key | T | Value to locate. |
Return Value
int
Matching index or negative encoded insertion position.
Working Example
Example Snippetjava
import java.util.*;public class Main {
public static void main(String[] args) { List<Integer> sizes = List.of(10, 20, 40, 50); System.out.println(Collections.binarySearch(sizes, 40)); int missing = Collections.binarySearch(sizes, 30); System.out.println(missing); System.out.println(-(missing + 1)); int[] codes = {2, 5, 9}; System.out.println(Arrays.binarySearch(codes, 1)); }}