← Back to course
Python 11-12 / Week 12 / Monday
1/6
Week 12 Β· Reading Java II and Ship

Monday

ArrayList
// ArrayList, sorting, searching and recursion in Java; then a code review and the FieldSim release
⏱ about 30 min

Monday: ArrayList

Comet opens the last week of FieldSim with a grin. "Pip carries a list of samples. A Java array has a fixed length, so how would Java carry them?"

Wren flips back through his clipboard. "What does the evidence say? Pip picks samples up one at a time. The list has to grow."

Nova projects ListDemo.java beside the Python list of samples. "How can I help?" she asks. "Java has a resizable list too. It is called ArrayList."

Comet reads the Java and laughs. "It says add where we say append."

"Then let us match every line," Wren says, and hands you a pencil.

Java's resizable list

ArrayList is Java's resizable list. The add method appends an item to the end. The get method reads the item at a position, and size counts the items.

An ArrayList can grow and shrink, and it holds object references. Java needs an import statement to use it.

ListDemo uses the Sample.java class from last week. The samples are made-up data from the FieldSim story.

// ListDemo.java
// An ArrayList of Sample objects, like a Python list of Samples.
import java.util.ArrayList;

public class ListDemo {
    public static void main(String[] args) {
        ArrayList<Sample> found = new ArrayList<Sample>();
        found.add(new Sample("S01", "basalt", 42));
        found.add(new Sample("S02", "quartz", 18));
        found.add(new Sample("S04", "mica", 7));
        int total = 0;
        for (Sample s : found) {
            total += s.getGrams();
        }
        System.out.println(found.size() + " samples");
        System.out.println(found.get(1).describe());
        System.out.println("Total: " + total + " g");
    }
}
PREDICT LISTDEMO
  • Read the question.
  • Tap your answer.
What does found.size() give after the three add calls?
found.get(1) reads position 1. Which sample is it?
Which line brings ArrayList into the program?

Here is what ListDemo printed when Nova ran it:

3 samples
S02 quartz 18 g
Total: 67 g

The Python twin

# list_twin.py
# The Python twin of ListDemo.java.
from sample import Sample

found = []
found.append(Sample("S01", "basalt", 42, 0, 2))
found.append(Sample("S02", "quartz", 18, 2, 4))
found.append(Sample("S04", "mica", 7, 4, 5))
total = 0
for s in found:
    total += s.grams
print(len(found), "samples")
print(found[1].describe())
print("Total:", total, "g")
3 samples
S02 quartz 18 g at (2, 4)
Total: 67 g
Python (list_twin.py)Java (ListDemo.java)
found = []ArrayList<Sample> found = new ArrayList<Sample>();
found.append(...)found.add(...);
found[1]found.get(1)
len(found)found.size()
for s in found:for (Sample s : found) {
total += s.gramstotal += s.getGrams();
At your computer
1. Type list_twin.py in your fieldsim folder and run it.
2. Append a fourth sample, Sample("S03", "clay", 65, 3, 0), before the total loop. Predict the three lines, then run it.
3. Now change found[1] to found[4]. Run it and read the error calmly.
4. Change it back to found[1] and run it again.
# list_twin.py
# The Python twin of ListDemo.java.
from sample import Sample

found = []
found.append(Sample("S01", "basalt", 42, 0, 2))
found.append(Sample("S02", "quartz", 18, 2, 4))
found.append(Sample("S04", "mica", 7, 4, 5))
found.append(Sample("S03", "clay", 65, 3, 0))
total = 0
for s in found:
    total += s.grams
print(len(found), "samples")
print(found[4].describe())
print("Total:", total, "g")
4 samples
Traceback (most recent call last):
  File "list_twin.py", line 14, in <module>
    print(found[4].describe())
          ~~~~~^^^
IndexError: list index out of range
What is the name of this error?
Which ArrayList method counts the items, like len in Python?
StatementTrue or false?
An ArrayList can grow as items are added.?
Java needs an import to use ArrayList.?
found.get(1) reads the first item added.?
A Java array and an ArrayList both have a fixed length.?
WHY THIS EXERCISEAn ArrayList is resizable and needs an import. Positions start at 0, and only an array has a fixed length.

You matched a Java ArrayList to your own Python list, lead programmer. Tomorrow the crew's sort and search go Java too.