CKTIS / Java
Linear search in Java
Linear search in Java: Linear search in Java examines elements in sequence until a match; List.indexOf uses equals and returns the lowest matching index or -1.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
linear searchLinear search in Java examines elements in sequence until a match; List.indexOf uses equals and returns the lowest matching index or -1.
Use it for a small or unsorted sequence, a one-off query, or a predicate for which no useful index exists.
Calling get(i) in a loop over LinkedList turns a linear scan into O(n²); use Iterator or enhanced for, and Objects.equals for nullable values.
An empty sequence and an absent value yield -1, duplicates stop at the first match, and primitive arrays compare values with ==.
List.indexOf reports the first blue as first-blue=1 and absence as missing=-1; the custom scan stops at green@2,checks=3 after three comparisons.
Examples
import java.util.List;
public class Main {
static int checks;
static int findLength(List<String> values, int length) {
for (int i = 0; i < values.size(); i++) {
checks++;
if (values.get(i).length() == length) return i;
}
return -1;
}
public static void main(String[] args) {
var values = List.of("red", "blue", "green", "blue");
System.out.println("first-blue=" + values.indexOf("blue"));
System.out.println("missing=" + values.indexOf("black"));
int index = findLength(values, 5);
System.out.println(values.get(index) + "@" + index + ",checks=" + checks);
}
}
Result
first-blue=1 missing=-1 green@2,checks=3
List.indexOf reports the first blue as first-blue=1 and absence as missing=-1; the custom scan stops at green@2,checks=3 after three comparisons.