Skip to content
Lesson 10 of 15

Step 1 of 5 · Reading · ~4 min

Learn

Collections

Arrays and ArrayList

Real programs handle sequences of values. Java offers the array (fixed size, minimal, fast) and the ArrayList (growable, more convenient). By the end of this lesson you can store, scan and filter a sequence, produce output with separators between items, and avoid the common index and seed mistakes.

Arrays: fixed size, direct access

int[] temps = {4, -2, 7, 0};      // literal
int[] zeros = new int[10];        // 10 slots, all 0

System.out.println(temps.length); // 4  -- a field, no parentheses
System.out.println(temps[1]);     // -2 -- indexes start at 0
temps[3] = 99;                    // write by index

The size is fixed at creation. Valid indexes run from 0 to length - 1; anything else throws ArrayIndexOutOfBoundsException at runtime:

temps[4] = 1;      // crash: only 0..3 exist

Walk an array by index when you need positions, or with for-each when you only need the values:

for (int i = 0; i < temps.length; i++) { ... temps[i] ... }
for (int t : temps) { ... t ... }

length, length() and size()

Three containers, three spellings, and everyone mixes them up for the first month:

array.length       // arrays: a field
string.length()    // Strings: a method
list.size()        // ArrayList and other collections: a method with another name

ArrayList: when the count is not known in advance

import java.util.ArrayList;

ArrayList<Integer> cold = new ArrayList<>();
for (int t : temps) {
    if (t < 0) {
        cold.add(t);                 // grows as needed
    }
}
System.out.println(cold.size());     // 1
System.out.println(cold.get(0));     // -2

<Integer> is a generic type parameter: this list holds Integer objects. It must be the wrapper Integer, never int; Java auto-converts int values on the way in and out. The list starts empty, and isEmpty() says whether it still is. Rule of thumb: known fixed size, use an array; building a result of unknown size, use an ArrayList.

Scanning: the best-so-far pattern, and its seed

Many tasks walk a sequence while tracking a summary. The trap is what you start the tracker at:

// BROKEN: 0 may not be in the data
int smallest = 0;
for (int t : temps) {
    if (t < smallest) smallest = t;
}
// for {4, 9, 7} this prints 0, a value that is not there
// CORRECT: seed with the first element
int smallest = temps[0];
for (int i = 1; i < temps.length; i++) {
    if (temps[i] < smallest) smallest = temps[i];
}

Seeding with 0 silently assumes the data crosses zero. Seed with an element of the data.

Printing with separators

To print values with a space between them, but none after the last, add the separator before every item except the first:

StringBuilder row = new StringBuilder();
for (int i = 0; i < cold.size(); i++) {
    if (i > 0) {
        row.append(' ');
    }
    row.append(cold.get(i));
}
System.out.println(row);

Printing x + " " for each item leaves a trailing space, which an exact-match grader treats as a different line. String.join(" ", ...) does the same job when you already hold Strings.

Two passes

Some questions cannot be answered in one pass, because deciding about item 1 needs information from the end of the data (the largest value, the total, the average). Store the whole sequence first, compute the summary, then loop a second time to act on each item with it.

Splitting a line of input

line.split(" ") turns "4 -2 7 0" into the String[] {"4", "-2", "7", "0"}. Convert each piece with Integer.parseInt.

Common mistakes

  • Off-by-one on the last index: i <= temps.length reads one slot too far.
  • .length versus .length() versus .size().
  • Seeding a minimum or maximum with 0.
  • A trailing separator in the printed line.
  • Summing a sequence in an int when the values are large; use long for totals.

Your exercise

Pick out the items that stand above the average of the whole list, keeping their original order. You cannot decide about the first item until you have seen the last, so this is a two-pass task with a result of unknown size. Compare carefully: how you test "above the average" must not lose information for negative numbers or overflow for big ones.

Up nextHashMapCollections

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…