Before the questions, make sure you can: create an array of objects and explain why its elements
start as null; declare and use an ArrayList with the correct generic type; use
add, get, set, remove, size, contains, indexOf and
isEmpty, including the difference between remove(int) and remove(Object); explain
autoboxing in a collection; say why String concatenation in a loop is wasteful and what
StringBuilder does instead; and predict the output of code that mixes append,
insert, delete and reverse.
Arrays of objects
Student[] roll = new Student[3]; // three NULL references, no Student objects yet
roll[0] = new Student("Ali", 65.5); // now there is one
System.out.println(roll[1].getName()); // NullPointerException: roll[1] is still null
for (int i = 0; i < roll.length; i++) roll[i] = new Student(); // fill the array first
Creating the array and creating the objects are two separate jobs. Forgetting the second is the most common run-time failure in this part of the course.
ArrayList: a resizable array
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>(); // <> = generic type; <String> not <string>
names.add("Ali"); // append at the end
names.add(0, "Sara"); // insert at index 0, shifting the rest right
names.set(1, "Hamza"); // replace the element at index 1
names.get(0); // read; indices from 0 to size()-1
names.size(); // a METHOD -- arrays use the field length
names.remove(0); // remove BY INDEX, shifting the rest left
names.remove("Ali"); // remove BY VALUE (first occurrence); returns boolean
names.contains("Ali"); // true/false
names.indexOf("Ali"); // index or -1
names.isEmpty(); names.clear();
| Array | ArrayList |
|
|---|---|---|
| Size | fixed at creation | grows and shrinks automatically |
| Size query | a.length (field) |
list.size() (method) |
| Element access | a[i] |
list.get(i), list.set(i, v) |
| Element type | primitives or objects | objects only (primitives are autoboxed) |
Autoboxing: ArrayList<Integer> nums; nums.add(5); silently wraps the int in an
Integer, and int x = nums.get(0); unwraps it. This creates the classic trap:
list.remove(2) removes the element at index 2, while list.remove(Integer.valueOf(2))
removes the value 2.
Removing while looping forward shifts the remaining elements left, so the loop skips one. Either
loop backwards, or use an Iterator.
StringBuilder: a mutable string
String objects are immutable (Chapter 5), so s += x inside a loop builds and discards a
new object on every pass. StringBuilder modifies one object in place:
StringBuilder sb = new StringBuilder("Java");
sb.append(" SE"); // "Java SE" -- returns the SAME object, so it can be chained
sb.insert(0, ">> "); // ">> Java SE"
sb.delete(0, 3); // "Java SE" -- start inclusive, end exclusive
sb.reverse(); // "ES avaJ"
sb.length(); // number of characters
String result = sb.toString();
Every one of those methods returns the builder itself, which is why sb.append("a").append("b")
works. Note that String has no reverse method at all: "abc".reverse() does not
compile.
Objects inside collections
ArrayList<Student> cohort = new ArrayList<>();
cohort.add(new Student("Ali", 65.5));
for (Student s : cohort) s.displayInfo(); // for-each over objects
double best = 0;
for (Student s : cohort) if (s.getGrade() > best) best = s.getGrade();
contains and indexOf use equals, so they only work as expected for your own classes
when equals has been overridden (Chapter 11).
new Student[5]creates fivenulls, not five students.size()for a list,lengthfor an array,length()for a string.remove(int)is by index;remove(Object)is by value.ArrayListstores objects only — primitives are autoboxed.StringBuilderchanges one object;Stringmethods create new ones.Stringhas noreverse,appendordelete.
ArrayList<int>does not compile; useArrayList<Integer>.- Calling
get(size())— the last index issize() - 1. - Removing inside a forward loop and skipping elements.
- Forgetting
import java.util.ArrayList;. - Building a long string with
+=inside a loop over thousands of items.
Ready? Close the notes and practise.
37 questions. Predict the output before you check — that is the skill the exam measures.