Arrays: Bulk Storage

Arrays: Bulk Storage in Java: A tool case comes with a foam insert, and the foam is milled once, at the factory, with exactly eight pockets.

The Analogy: The Milled Foam Insert In A Tool Case

A tool case comes with a foam insert, and the foam is milled once, at the factory, with exactly eight pockets. Each pocket is cut to the outline of one spanner. You cannot mill a ninth pocket into a case that is already closed and sold, and you cannot press a hammer into a pocket shaped for a 10mm spanner. The count and the shape were both decided before the case ever reached you, and neither is up for discussion afterwards.

The pockets are numbered along the top edge of the foam, and the engraver started his ruler at the left edge, so the first pocket is marked 0 and the last of eight is marked 7. Position is the only name a tool has here. "The 10mm spanner" is not how you find anything -- "pocket 3" is. And asking for pocket 8 is not asking for an empty pocket. It is pointing at the wall behind the case, and the right response is to stop, not to hand over whatever is there.

An empty pocket is still a pocket, and it already has a defined state before anything is put in it. On the metal side of the case an empty pocket is visibly, measurably empty. On the paper side, where index cards live, an empty slot holds a blank card. Java is just as literal about this: a new int[] arrives with every slot holding 0, a new boolean[] with every slot false, and a new String[] with every slot null. Those are guarantees written into the language, not leftovers from whatever was in memory.

The failures follow from the two hard rules. Reaching past the last pocket is the off-by-one, and Java stops you at the moment you reach rather than letting you read the wall. Writing a second label with the same case serial and handing it to a colleague does not produce a second case, so when they rearrange "their" tools yours move too -- that is two variables holding one array, and it is the single most expensive misunderstanding in this lesson. And a case cannot grow: getting a ninth pocket means milling a whole new insert and moving the tools across, which is exactly what "resizing an array" means in Java, and anyone still holding the old label is still looking at the old eight-pocket case.


Syntax or Core Structure

An array is created with a length that can never change. There are three ways to write one down, and length is a field, not a method call.

import java.util.Arrays;

public class Store {
    public static void main(String[] args) {
        int[] counts = new int[4];
        String[] names = new String[3];
        int[] fixed = { 7, 8, 9 };
        double[][] grid = new double[2][3];

        counts[0] = 12;
        counts[3] = 5;
        names[1] = "beta";
        grid[1][2] = 0.5;

        System.out.println("length   " + counts.length);
        System.out.println("counts   " + Arrays.toString(counts));
        System.out.println("names    " + Arrays.toString(names));
        System.out.println("fixed    " + Arrays.toString(fixed));
        System.out.println("rows     " + grid.length);
        System.out.println("cols     " + grid[0].length);
        System.out.println("cell     " + grid[1][2]);
        System.out.println("deep     " + Arrays.deepToString(grid));
    }
}

Output:

length   4
counts   [12, 0, 0, 5]
names    [null, beta, null]
fixed    [7, 8, 9]
rows     2
cols     3
cell     0.5
deep     [[0.0, 0.0, 0.0], [0.0, 0.0, 0.5]]

The zeros in counts and the nulls in names were never assigned by this program; they are the guaranteed defaults for those element types. counts.length has no parentheses because it is a final field on the array object -- String uses the method length() and List uses size(), and Java gives you all three spellings for the same idea. The brace form { 7, 8, 9 } only works at the point of declaration; assigning to an existing variable later needs new int[] { 7, 8, 9 }. And a double[2][3] is not a rectangle in memory -- it is an array of two references, each pointing at its own double[3], which is why grid[0].length is a sensible question to ask and why Arrays.deepToString exists at all.


Technical Depth: What An Array Variable Actually Holds, And Why Length Is Not Negotiable

The variable holds a reference; assignment does not copy anything

int[] a = { 1, 2, 3 };
int[] b = a;
int[] c = a.clone();

b[0] = 99;

System.out.println("a        " + Arrays.toString(a));
System.out.println("b        " + Arrays.toString(b));
System.out.println("c        " + Arrays.toString(c));
System.out.println("alias    " + (a == b));
System.out.println("clone eq " + (a == c));
System.out.println("dot eq   " + a.equals(c));
System.out.println("arrays   " + Arrays.equals(c, new int[] { 1, 2, 3 }));

Output:

a        [99, 2, 3]
b        [99, 2, 3]
c        [1, 2, 3]
alias    true
clone eq false
dot eq   false
arrays   true

Three lines of setup and three separate lessons. b = a produced a second name for one array, so writing through b changed a; nothing was copied and nothing warned you. a.clone() produced a genuinely separate array, which is why c still reads 1 at index 0. And a.equals(c) is Object.equals -- arrays do not override it -- so it answers "are these the same object", which is why comparing array contents needs Arrays.equals.

OperationCopies elementsAllocatesLengthNote
b = anonosame arraytwo names, one array
a.clone()yesyessame as sourceshallow
Arrays.copyOf(a, n)yesyesexactly npads with defaults or truncates
Arrays.copyOfRange(a, i, j)yesyesj - ihalf-open, j is excluded
System.arraycopy(...)yesnointo an array you supplyfastest, no bounds guessing

Every copy in that table is shallow

StringBuilder[] src = { new StringBuilder("x"), new StringBuilder("y") };
StringBuilder[] cp = src.clone();

cp[0].append("!");

System.out.println("src[0]   " + src[0]);
System.out.println("cp[0]    " + cp[0]);
System.out.println("same arr " + (src == cp));
System.out.println("shared   " + (src[0] == cp[0]));

Output:

src[0]   x!
cp[0]    x!
same arr false
shared   true

The two arrays are different objects, and they hold the same two references. clone() copies the slots, not the things in them. For an int[] that distinction does not exist and clone() is a full copy; for any array of objects it means a "copy" that shares every element, and mutating an element through either array is visible through both. A deep copy has to be written by hand, element by element.

length is final, so growing means replacing

int[] small = { 1, 2 };
int[] grown = Arrays.copyOf(small, 4);
int[] cut = Arrays.copyOfRange(small, 1, 2);

System.out.println("grown    " + Arrays.toString(grown));
System.out.println("cut      " + Arrays.toString(cut));
System.out.println("small    " + Arrays.toString(small));
System.out.println("lengths  " + small.length + " " + grown.length + " " + cut.length);

Output:

grown    [1, 2, 0, 0]
cut      [2]
small    [1, 2]
lengths  2 4 1

Neither call changed small; both allocated a new array and copied into it. This is the whole cost model. Appending one element to an array of n means allocating n + 1 slots and copying n of them, so building a list by repeated copyOf is quadratic. ArrayList exists precisely to amortise that -- it keeps a larger array than it needs and only reallocates when it fills up. Use an array when the size is settled; use a list when it is not.

Three checks that happen at runtime, not at compile time

int[] a = new int[3];
int n = -1;

String over = "none";
String neg = "none";
String store = "none";

try {
    a[3] = 1;
} catch (ArrayIndexOutOfBoundsException e) {
    over = "caught";
}

try {
    int[] bad = new int[n];
    bad[0] = 1;
} catch (NegativeArraySizeException e) {
    neg = "caught";
}

Object[] refs = new String[2];
try {
    refs[0] = Integer.valueOf(7);
} catch (ArrayStoreException e) {
    store = "caught";
}

System.out.println("over     " + over);
System.out.println("negative " + neg);
System.out.println("store    " + store);
System.out.println("kind     " + refs.getClass().getSimpleName());

Output:

over     caught
negative caught
store    caught
kind     String[]

The third one is the interesting one. String[] is assignable to Object[] -- Java arrays are covariant -- so the compiler is perfectly happy with refs[0] = Integer.valueOf(7), because as far as the static types go you are putting an Object into an Object[]. The array itself remembers what it was made of and refuses at runtime. That hole is why generics were made invariant and why a List<String> is not a List<Object>: the same mistake with lists is a compile error instead of an ArrayStoreException in production.

Sorting and searching

int[] readings = { 40, 12, 99, 3, 12 };
int[] sorted = readings.clone();
Arrays.sort(sorted);

int at = Arrays.binarySearch(sorted, 40);
int miss = Arrays.binarySearch(sorted, 41);

int sum = 0;
for (int r : readings) {
    sum += r;
}

System.out.println("raw      " + Arrays.toString(readings));
System.out.println("sorted   " + Arrays.toString(sorted));
System.out.println("found 40 " + at);
System.out.println("miss 41  " + miss);
System.out.println("sum      " + sum);

Output:

raw      [40, 12, 99, 3, 12]
sorted   [3, 12, 12, 40, 99]
found 40 3
miss 41  -5
sum      166

Arrays.sort sorts in place, which is why readings was cloned first -- a method that quietly reorders its caller's array is a bug waiting for its second caller. binarySearch returns the index when it finds the value, and when it does not, it returns the negated insertion point minus one: 41 belongs at index 4, so the answer is -5. That encoding lets one call answer both "is it there" and "where would it go", and it is the reason the return value must be tested with < 0 rather than == -1.

The rule binarySearch cannot enforce is that the array must already be sorted. Called on unsorted input it does not fail; it returns an unspecified answer, confidently, and a duplicate value gives no guarantee about which of the equal elements you get.


Real World Example: A Ring Buffer For The Last Five Pressure Readings

A sensor reports a pressure every few seconds, forever, and a diagnostic screen needs the most recent five. The fixed length of an array is not a limitation here -- it is the specification. Memory is bounded by construction, nothing allocates after startup, and the policy for what happens when the buffer is full has to be written down rather than left to a container that grows quietly.

import java.util.Arrays;
import java.util.Locale;

public class Trace {

    private static final int CAPACITY = 5;

    private final int[] slots = new int[CAPACITY];
    private int next = 0;
    private int written = 0;

    void record(int bar) {
        slots[next] = bar;
        next = (next + 1) % CAPACITY;
        written++;
    }

    int size() {
        return Math.min(written, CAPACITY);
    }

    // Oldest first, newest last. Always a fresh array.
    int[] snapshot() {
        int n = size();
        int[] out = new int[n];
        int start = (written <= CAPACITY) ? 0 : next;
        for (int i = 0; i < n; i++) {
            out[i] = slots[(start + i) % CAPACITY];
        }
        return out;
    }

    public static void main(String[] args) {
        int[] feed = { 31, 34, 30, 41, 47, 52, 49 };
        Trace t = new Trace();

        for (int i = 0; i < feed.length; i++) {
            t.record(feed[i]);
            System.out.println(String.format(Locale.ROOT,
                    "tick %d  bar %2d  size %d  window %s",
                    i + 1, feed[i], t.size(), Arrays.toString(t.snapshot())));
        }

        int[] window = t.snapshot();
        int peak = window[0];
        int sum = 0;
        for (int bar : window) {
            if (bar > peak) {
                peak = bar;
            }
            sum += bar;
        }

        System.out.println("written  " + t.written);
        System.out.println("kept     " + window.length);
        System.out.println("dropped  " + (t.written - window.length));
        System.out.println("peak     " + peak);
        System.out.println("mean     "
                + String.format(Locale.ROOT, "%.1f", (double) sum / window.length));
        System.out.println("raw      " + Arrays.toString(t.slots));
    }
}

Output:

tick 1  bar 31  size 1  window [31]
tick 2  bar 34  size 2  window [31, 34]
tick 3  bar 30  size 3  window [31, 34, 30]
tick 4  bar 41  size 4  window [31, 34, 30, 41]
tick 5  bar 47  size 5  window [31, 34, 30, 41, 47]
tick 6  bar 52  size 5  window [34, 30, 41, 47, 52]
tick 7  bar 49  size 5  window [30, 41, 47, 52, 49]
written  7
kept     5
dropped  2
peak     52
mean     43.8
raw      [52, 49, 30, 41, 47]

Two integers carry all the state that the array itself cannot. next is a write cursor and it wraps -- it is never a count of anything, and reading it as one is the classic misunderstanding of this data structure. written is a count of events and it never wraps, which is what lets size() distinguish the warm-up phase from steady state and lets snapshot() decide where the oldest reading currently lives. Everything else the class does is one modulo operation.

The last line of output is the reason snapshot() has to exist. raw is the physical layout, and after seven readings it holds 52 and 49 at the front and the older figures behind them -- the buffer is not in chronological order and never will be. Any caller given the underlying array directly would have to know about next to interpret it, and would also be free to write into it. Returning a freshly allocated, correctly ordered copy is what turns the wrap from a caller's problem back into an implementation detail.

dropped 2 is the accounting a ring buffer owes its user. Its contract is "the oldest data will be discarded", which is a perfectly good contract only as long as the discarding is visible. Without that line the screen shows five readings that look exactly like a complete history, and a five-reading window is indistinguishable from five readings ever having happened. Any container with an eviction policy needs a counter for what it evicted.

The honest limits, and there is a real one hiding in plain sight. written is an int, and at one reading a second this program runs for about sixty-eight years before it overflows -- but at a thousand a second it is under a month, and when it overflows it goes negative, written <= CAPACITY becomes true again, and snapshot() silently starts reading from index 0 and returning the window in the wrong order. It should be a long, and even then the dropped subtraction wants thinking about. Beyond that: nothing here is synchronised, so two threads calling record will interleave the slot write and the cursor update and lose entries with no error at all, and the class's API says nothing about being single-threaded. peak = window[0] throws ArrayIndexOutOfBoundsException on a buffer that has recorded nothing, which is the ordinary startup case. And snapshot() allocates on every call, so a screen polling it at 1kHz produces garbage in proportion to capacity -- invisible at five slots, a real problem at a hundred thousand.


Common Mistakes

  1. Writing array.length(). Arrays expose a length field with no parentheses, String exposes a length() method, and List exposes size(). Three spellings for one idea, and the compiler will only help you with two of them.
  1. Looping to i <= array.length. The valid indices are 0 through length - 1. This walks one slot past the end and throws -- after having processed everything else correctly, which is why the bug usually surfaces as half-written data.
  1. Expecting b = a to copy. It creates a second name for the same array. Every write through either name is visible through both, and there is no warning at compile time or run time. Use clone() or Arrays.copyOf.
  1. Comparing arrays with == or .equals(). Both ask whether the two references point at the same object. Use Arrays.equals for one dimension and Arrays.deepEquals for nested arrays -- and note that Arrays.equals on a String[][] compares the row references, not the rows.
  1. Printing an array directly. System.out.println(arr) prints a type tag and an identity hash, which is different on every run and tells you nothing. Use Arrays.toString for one dimension and Arrays.deepToString for more.
  1. Calling Arrays.binarySearch on unsorted input. It does not detect the problem and does not throw; it returns a plausible wrong answer. Sort first, or use a linear scan.
  1. Assuming a two-dimensional array is rectangular. new int[3][] creates three null rows, and rows created separately can have different lengths. Always use grid[r].length for the inner bound, never grid[0].length.
  1. Forgetting that object arrays start out full of nulls. new String[3] is not three empty strings; calling .length() on element 0 throws NullPointerException. Only primitive arrays arrive with a usable default.
  1. Using an array for a collection whose size changes. Every append means allocating a new array and copying the old one, so building a list that way is quadratic. That is what ArrayList is for, and it is not slower than a hand-rolled array for anything but the tightest numeric loops.

Best Practices

  • Choose an array when the length is fixed and known, and a List when it is not. A ring buffer, a lookup table, a fixed-width record: array. Anything that accumulates: list.
  • Never hand out the live array from a getter. Return slots.clone() or an unmodifiable view. An array field with a public getter is a public mutable field wearing a method's clothing.
  • Log with Arrays.toString and Arrays.deepToString. An identity hash in a log line is worse than no log line, because it looks like information.
  • Prefer the enhanced for when the index is not part of the work. It cannot be given the wrong bound and cannot walk off the end, which removes two of the three bugs in this lesson.
  • Use the library for copies. Arrays.copyOf, Arrays.copyOfRange and System.arraycopy are correct, intrinsified and clear about their bounds; a hand-written copy loop is three chances to be off by one.
  • Remember that every built-in copy is shallow. For arrays of objects, a clone() shares every element. If the elements are mutable and the copy is meant to be independent, copy them yourself.
  • Sort a clone unless reordering the caller's data is the documented purpose. Arrays.sort is in place, and a method that reorders its argument as a side effect will surprise its second caller, never its first.
  • Prefer List<T> to T[] in public signatures. Arrays are mutable, covariant and impossible to make immutable, and the covariance hole turns a type error into a runtime ArrayStoreException.

Practice Exercises

  1. The Alias Trap. Write a Meter class with a private int[] readings field and a getReadings() that returns the field directly. From main, call the getter, write into slot 0 of what you got back, then print the meter's own view and show that you changed its private state from outside. Fix it by returning readings.clone(), prove the fix, and then explain in one sentence why the same fix is not enough if the elements are StringBuilder instead of int.
  1. The Overflow Clock. Add a constructor to Trace that sets written directly, start it at Integer.MAX_VALUE - 2, and record five readings. Print written, size(), dropped and the window after each one, and describe exactly which output line first becomes wrong and why. Then change written to a long, adjust size() and the dropped subtraction, and show the same run behaving correctly.
  1. The Jagged Grid. Build int[][] grid = new int[3][] with rows of length 1, 2 and 3, fill it with consecutive numbers, and sum it with nested loops that use grid[r].length as the inner bound. Print the total and Arrays.deepToString. Then replace the inner bound with grid[0].length and report what happens and what the total becomes -- and say which of the two failures you would rather have in production.