Collections.binarySearch is logarithmic but assumes sorted input. On unsorted data the result is meaningless, and a miss returns a negative insertion point.
var sorted = new ArrayList<>(List.of(10, 20, 30, 40, 50));
System.out.println("index of 30 = " + Collections.binarySearch(sorted, 30));
int miss = Collections.binarySearch(sorted, 35);
System.out.println("miss returns " + miss + ", insertion point = " + (-miss - 1));
sorted.add(-miss - 1, 35);
System.out.println("inserted in order: " + sorted);
index of 30 = 2
miss returns -4, insertion point = 3
inserted in order: [10, 20, 30, 35, 40, 50]
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30