bhylu.com

Advertisements

Java Use Library Algorithms with Their Preconditions

An algorithm helper can simplify code only when its preconditions match the data. Searching a sorted list and scanning an unsorted list solve different problems.

Understand the idea

Collections includes operations such as binarySearch, reverse, rotate, min and max. Some mutate the supplied list; others return an answer. binarySearch requires the data to be sorted according to a compatible ordering. A negative result encodes an insertion point, not simply the index -1. Read each operation’s mutation and optional-operation requirements before using an unmodifiable collection.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        List<Integer> sizes = new ArrayList<>(List.of(8, 2, 5));
        Collections.sort(sizes);
        System.out.println(sizes);
        System.out.println(Collections.binarySearch(sizes, 5));
        Collections.rotate(sizes, 1);
        System.out.println(sizes);
    }
}

Expected output

[2, 5, 8]
1
[8, 2, 5]

Sorting establishes the search precondition. Five is at index one in the sorted list. Rotation then changes the order and invalidates that sortedness for future natural-order binary searches. The collection type did not change; the relevant data invariant did.

Check the official Java documentation for detailed contracts and supported options.