An index trades preparation and memory for faster repeated lookups. The useful skill is choosing the data structure for the workload, not memorizing that one collection is always faster. We will count inspected entries instead of relying on noisy browser timings.
Understand the contract
A list search may inspect every entry for one missing key. Repeating that search for many queries repeats the scan. A map index stores each key once so later lookups avoid a full list traversal. Building it still takes work, uses memory, and must decide what duplicate keys mean.
Big-O notation describes how work grows with input size, ignoring fixed factors. A linear scan is O(n) for n entries in the worst case. Building a hash map is typically O(n), with expected O(1) lookup afterward under ordinary hashing conditions. Those are growth models, not promises about milliseconds or a guarantee that an index is worthwhile for a single query.
The first example counts comparisons for a missing key. The second uses a map and separates building from querying. The third counts both approaches at three sizes so you can see the work grow. Neither changes its source. An index can become stale if the source changes after construction; prefer immutable records, rebuild deliberately, or centralize updates in the owner. Two independently writable copies need an explicit synchronization policy.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> ids = List.of("A", "B", "C");
int inspected = 0;
boolean found = false;
for (String id : ids) {
inspected++;
if (id.equals("missing")) {
found = true;
break;
}
}
System.out.println(found);
System.out.println(inspected);
}
}Check your prediction
false
3Trace a different case
A map is not a free extra view over a list: this example builds a separate container. Its values are immutable strings, so sharing them is safe. Map.get does not report how much work it did internally. Test lookup correctness and duplicate policy here; the next section counts calls instead, which is enough to compare how the two approaches grow.
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
List<String> ids = List.of("A", "B", "C");
Map<String, String> index = new LinkedHashMap<>();
for (String id : ids) {
index.put(id, "Title " + id);
}
System.out.println(index.get("C"));
System.out.println(index.containsKey("missing"));
System.out.println(ids.size());
}
}Check your prediction
Title C
false
3Count the work as the input grows
One scan of three items proves nothing about growth. The program below runs the
same workload at three sizes: n items, and n queries that each look up one
existing ID. The scan counts every item it compares. The index counts one
operation per put while building and one per get. Predict the scan column
before running: the query for the k-th ID inspects k items.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
for (int size : new int[] {10, 100, 1000}) {
List<String> ids = new ArrayList<>();
for (int number = 0; number < size; number++) {
ids.add("ID" + number);
}
System.out.println(size + " items, " + size + " queries: scan "
+ scanInspections(ids, ids) + ", index " + indexOperations(ids, ids));
}
}
static long scanInspections(List<String> ids, List<String> queries) {
long inspected = 0;
for (String query : queries) {
for (String id : ids) {
inspected++;
if (id.equals(query)) {
break;
}
}
}
return inspected;
}
static long indexOperations(List<String> ids, List<String> queries) {
long operations = 0;
Map<String, Integer> index = new HashMap<>();
for (int position = 0; position < ids.size(); position++) {
index.put(ids.get(position), position);
operations++;
}
for (String query : queries) {
index.get(query);
operations++;
}
return operations;
}
}Check your prediction
10 items, 10 queries: scan 55, index 20
100 items, 100 queries: scan 5050, index 200
1000 items, 1000 queries: scan 500500, index 2000| n | scan inspections | index operations | ratio |
|---|---|---|---|
| 10 | 55 | 20 | about 3× |
| 100 | 5,050 | 200 | about 25× |
| 1,000 | 500,500 | 2,000 | about 250× |
Each tenfold increase in n multiplies the scan's work by about 100, because both
the number of queries and the length of each scan grew: that is n²/2, the
quadratic growth Big-O names. The index grows by 10, because building is n puts
and each query is one get. Be precise about what the index column counts: a
get does some hashing and comparing internally, but that work does not grow
with n under ordinary hashing, so one operation per call is a fair model. It is
a model of growth, not a stopwatch.
Include preparation and maintenance in the tradeoff
The same table turns around for other workloads. With one query, the scan inspects at most n items while the index pays n puts before its first get, so the scan wins. And if the list changes between queries, every change means rebuilding the index: n more puts each time. An index pays off when many lookups share one build.
If callers can change source entries without updating the index, a fast lookup can be quickly wrong. Immutable values and one owner for updates make the relationship easier to maintain. A cached or secondary index introduces another invariant, not merely a new collection.
Build it yourself
Choose scan or index for a workload
A workload is described by three numbers: items in the list, queries to answer, and rebuilds (times the list changes between queries, each forcing the index to be rebuilt). Use the lesson's cost model, worst case for the scan:
- scan cost = items × queries, as in the table above;
- index cost: derive it from the lesson's counts. Building costs one put per item, every rebuild pays that again, and each query is one get.
Write scanCost, indexCost and choose, which returns "index" only when the
index is strictly cheaper; a tie goes to the simpler scan. Predict each choice
before you code it, then make the program print these four lines exactly:
1000/1/0: scan (scan 1000, index 1001)
1000/50/0: index (scan 50000, index 1050)
1000/200/199: scan (scan 200000, index 200200)
1000/200/3: index (scan 200000, index 4200)public class Main {
public static void main(String[] args) {
report(1000, 1, 0);
report(1000, 50, 0);
report(1000, 200, 199);
report(1000, 200, 3);
}
static void report(int items, int queries, int rebuilds) {
System.out.println(items + "/" + queries + "/" + rebuilds + ": "
+ choose(items, queries, rebuilds)
+ " (scan " + scanCost(items, queries)
+ ", index " + indexCost(items, queries, rebuilds) + ")");
}
static long scanCost(int items, int queries) {
return 0; // Replace with the scan formula.
}
static long indexCost(int items, int queries, int rebuilds) {
return 0; // Replace with the index formula.
}
static String choose(int items, int queries, int rebuilds) {
return "scan"; // Compare the two costs.
}
}Hint 1: the idea
The index's cost is mostly building it, and every rebuild pays that again. The scan's cost is paid per query. The choice depends on how many queries share one build.
Hint 2: a first step
Do the arithmetic in long. These four workloads fit in an int, but a larger
one, such as 1000 items × 1000000 queries, would overflow. Cast one operand, as
in (long) items * queries, before multiplying. Then write choose
with a single comparison using <, so ties fall through to "scan".
Show one solution
public class Main {
public static void main(String[] args) {
report(1000, 1, 0);
report(1000, 50, 0);
report(1000, 200, 199);
report(1000, 200, 3);
}
static void report(int items, int queries, int rebuilds) {
System.out.println(items + "/" + queries + "/" + rebuilds + ": "
+ choose(items, queries, rebuilds)
+ " (scan " + scanCost(items, queries)
+ ", index " + indexCost(items, queries, rebuilds) + ")");
}
static long scanCost(int items, int queries) {
return (long) items * queries;
}
static long indexCost(int items, int queries, int rebuilds) {
return (long) (rebuilds + 1) * items + queries;
}
static String choose(int items, int queries, int rebuilds) {
if (indexCost(items, queries, rebuilds) < scanCost(items, queries)) {
return "index";
}
return "scan";
}
}The first row shows that a single query never justifies an index: building it
costs as much as the scan before the first lookup. The third row shows
maintenance cost: the list changes before almost every query, so the index is
rebuilt 200 times and loses by 200. Change rebuilds to 3 and the same 200
queries make the index about 50 times cheaper. Using < rather than <= makes
the tie rule explicit, and long arithmetic keeps larger workloads from
overflowing.
Change it and test again
Find the smallest number of queries for which the index wins with 1000 items and no rebuilds, and explain the answer from the formulas. Then add memory to the decision: the index stores one extra entry per item. Describe a workload where the scan is still the right choice even though the index is cheaper in operations.
Explain before moving on
When could a scan be simpler and good enough? Who owns the index after construction? Explain why the browser engine's execution speed is not a JVM performance measurement and why a single stopwatch result cannot establish an algorithm's growth rate.
Completion is saved in this browser only. It does not measure mastery.