Collections of Objects
A library program might keep several books together so that it can update their availability or total their copies. A collection of objects groups references to objects so that you can access and process them together. Here, you will work with ordered collections: arrays and lists. The central distinction is between a position in the collection and the object that position refers to. They are separate things, and changing one does not always change the other.
Create the collection and its elements
Consider this Java class, whose objects record available copies of a book:
class Book {
int copies;
Book(int copies) {
this.copies = copies;
}
}Calling its constructor with new Book(4) creates one Book object. Creating an array is a separate operation:
Book[] books = new Book[3];
books[0] = new Book(4);
books[1] = books[0];
books[2] = new Book(9);The first line creates three reference slots, initially containing null. It does not create three Book objects. The later statements fill those slots, but only two statements create Book objects. Assigning books[0] to books[1] copies a reference rather than duplicating a book.
The following diagram shows the state after all four statements.
Follow references when making changes
Aliasing occurs when multiple references refer to the same object. In the diagram, positions zero and one provide two routes to Book A.
Example: Executing books[0].copies = 6 changes Book A. Reading books[1].copies then also gives 6 because both positions still refer to that object. A field update changes the shared object.
Now execute books[1] = new Book(3). This replaces the reference in position one with a reference to a new object. Position zero still refers to Book A, whose copies value remains 6. The three positions now report 6, 3 and 9.
Traverse and choose a collection
For a completely populated collection with n positions, let xi be the copies value reached through position i. The total over positions is
After the changes above, the total is 6+3+9=18 copies. Java can calculate it by visiting each element:
int total = 0;
for (Book book : books) {
total += book.copies;
}This loop requires every element to be non-null. If empty slots are permitted, check book != null before accessing book.copies. Also decide what your total represents: a traversal visits positions, so repeated references can count the same object more than once.
Arrays and lists offer different ways to manage those positions:
Collection | Replace an existing element? | Change the number of positions? |
|---|---|---|
Java array | Yes, with indexed assignment | No; create another array |
Java ArrayList | Yes, with set | Yes, with add or remove |
Scala Array | Yes, with indexed assignment | No; create another array |
Scala List | No; its structure is immutable | Produce another list |
Java arrays use books[0] and books.length; an ArrayList uses books.get(0) and books.size(). Scala uses books(0) for indexed access and books.length for length. For existing Book objects named bookA and bookB, Scala can construct Array(bookA, bookB) or List(bookA, bookB).
An immutable Scala List preserves its element references and order. It does not make mutable Book objects immutable: their fields can still change through shared references.
What to remember
- Creating reference slots does not create the element objects.
- Field updates affect every reference to the same object.
- Element replacement redirects one collection position.
- Traversal processes positions; check for empty or repeated references when interpreting results.
Example: Tracking supply bins
A school supply room uses a Java collection of objects to record the number of units in its bins. Each Bin object has a mutable integer field named units. The following statements run in order:
class Bin {
int units;
Bin(int units) {
this.units = units;
}
}
Bin[] bins = new Bin[3];
bins[0] = new Bin(11);
bins[1] = new Bin(6);
bins[2] = bins[0];The array records references, so two positions can lead to the same physical bin. Treat a total across positions as a programming calculation; repeated references would double-count a physical bin.
a) How many distinct Bin objects does the array refer to after this initialization?
- The array contains ________ occupied positions. Creating the array itself creates reference slots rather than Bin elements.
- Count the executed Bin constructor calls: one creates the bin with 11 units, and one creates the bin with 6 units.
- The final assignment copies an existing reference. It creates no additional Bin.
The array refers to 2 distinct Bin objects. The first and last positions demonstrate aliasing: multiple references lead to one object.
b) The program next executes bins[0].units -= 4;. What units value is now read through each position?
- The shared bin initially contains ________, and the statement removes ________. Its new value is 11−4=7 units.
- Positions zero and two both lead to this shared bin, so each now reports 7 units.
- Position one leads to a separate bin, which remains at 6 units.
The values at positions zero, one and two are 7 units, 6 units and 7 units, respectively. The update changes one object, but that change is visible through both references to it.
c) The program then executes bins[2] = new Bin(9);. Find the sum of units across all three array positions.
- The assignment creates a new Bin with 9 units and redirects position two. The array now refers to ________ distinct Bin objects. Replacing position two does not change the object reached through position zero.
- Positions zero and one contain 7 units and 6 units, giving an intermediate subtotal of ________.
- Add the new bin's 9 units:
The final sum across the array positions is 22 units. After this replacement, each position refers to a different Bin, so this sum also equals the total across the three referenced physical bins.
A recreation centre tracks bags in an array of lockers. Each Locker has an integer field bags, and new Locker(n) constructs an object containing n bags. This Java fragment runs inside a method:
Locker[] lockers = {
new Locker(2), null, new Locker(5), null
};
int total = 0;
for (Locker locker : lockers) {
total += locker.bags;
}Complete the description of a repair that ignores positions without objects. Use the Java literal for a missing object reference in the first blank and either before or after in the second.
The loop should skip an element when its value is . The check must occur accessing locker.bags.
A Java monitoring program stores Sensor objects in an array. Trace the complete fragment, then enter the final value field at each position and the number of distinct Sensor objects referenced by the array. Enter exact integers.
class Sensor {
int value;
Sensor(int value) {
this.value = value;
}
}
Sensor[] readings = new Sensor[3];
readings[0] = new Sensor(14);
readings[1] = new Sensor(9);
readings[2] = readings[0];
readings[1].value += 4;
readings[2] = new Sensor(6);
readings[0].value -= 3;| Entry | Final integer |
| Value at position 0 | |
| Value at position 1 | |
| Value at position 2 | |
| Distinct Sensor objects referenced |