0% found this document useful (0 votes)
2 views14 pages

ArrayList Notes

The document provides a comprehensive guide on Java's ArrayList, detailing its dynamic nature, core methods such as add(), remove(), get(), set(), and size(), as well as traversal techniques. It compares ArrayLists with standard arrays, highlighting their differences in size flexibility, element access, and memory efficiency. Additionally, it includes worked examples demonstrating practical applications of ArrayLists in Java programming.

Uploaded by

raissabugga
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

ArrayList Notes

The document provides a comprehensive guide on Java's ArrayList, detailing its dynamic nature, core methods such as add(), remove(), get(), set(), and size(), as well as traversal techniques. It compares ArrayLists with standard arrays, highlighting their differences in size flexibility, element access, and memory efficiency. Additionally, it includes worked examples demonstrating practical applications of ArrayLists in Java programming.

Uploaded by

raissabugga
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STANDARD LEVEL · B2.2.

Java ArrayList
Dynamic collections, core methods, traversal patterns, common errors, and exam technique

Contents
01 What is an ArrayList?
02 Array vs ArrayList — Comparison
03 The add() Method — Append & Insert
04 The remove() Method — Delete & Shift
05 The get() and set() Methods
06 The size() Method
07 Traversal — Looping Through a List
08 Worked Examples — Complete Programs
09 2D ArrayLists
10 Common Errors & Exam Tips
11 Quick Reference Summary
SECTION 01 — What is an ArrayList?

An ArrayList is a dynamic, resizable list in Java that stores an ordered sequence of objects. Unlike
a standard array whose size is fixed at creation, an ArrayList automatically grows when you add
elements and shrinks when you remove them. It belongs to the [Link] package and is one of the
most commonly used data structures in Java.
Term Definition
ArrayList A resizable-array implementation of the List interface. Stores elements in
insertion order, allows indexed access, and supports dynamic resizing.
Must be imported from [Link].

■ Required Import
You must include import [Link]; at the very top of every file that uses ArrayList — before
the class declaration. Forgetting this causes a compilation error.

Declaration Syntax
The ArrayList uses generics — a type parameter inside angle brackets that specifies what kind of
objects the list holds. The syntax is:
Java — Declaration

import [Link]; // Step 1: import

// Step 2: declare — syntax: ArrayList<Type> name = new ArrayList<>();


ArrayList<String> names = new ArrayList<>(); // holds Strings
ArrayList<Integer> scores = new ArrayList<>(); // holds Integers
ArrayList<Double> temps = new ArrayList<>(); // holds Doubles
ArrayList<Boolean> flags = new ArrayList<>(); // holds Booleans

■ Generics & Wrapper Classes


The type in angle brackets must be a reference (object) type — you cannot use primitive types like
int, double, or boolean. Instead use wrapper classes: Integer for int, Double for double, Character
for char, Boolean for boolean. Java's autoboxing automatically converts int to Integer and back, so
you can write [Link](85) even though the list stores Integer objects.

Complete First Example


Java — First Example

import [Link];
public class FirstExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link](fruits); // [Apple, Banana, Cherry]
[Link]([Link]()); // 3
}
}
SECTION 02 — Array vs ArrayList — Comparison

Both arrays and ArrayLists store ordered sequences of values. Understanding their differences is
essential for choosing the correct structure and for answering exam questions about when to use
each.

Feature Array ArrayList


Size Fixed at creation; cannot Dynamic — grows & shrinks
change automatically
Declaration int[] arr = new int[5]; ArrayList<T> list = new ArrayList<>();
Access element arr[i] [Link](i)
Update element arr[i] = x; [Link](i, x);
Size/length [Link] (property) [Link]() (method call)
Remove element Manual shifting required [Link](i);
Primitive types? Yes — stores directly No — must use wrapper classes
Import needed? No import [Link];
Memory More efficient for fixed data Slight overhead for resizing
IB exam use When size is fixed & known When size changes at runtime

Side-by-Side Code Comparison


Java — Array vs ArrayList

// ■■■ ARRAY ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


int[] scores = new int[3]; // size locked forever
scores[0] = 85;
scores[1] = 90;
scores[2] = 78;
// [Link] → always 3, even if values unused
// Cannot add a 4th score without creating a new array!

// ■■■ ARRAYLIST ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


ArrayList<Integer> marks = new ArrayList<>();
[Link](85); // size → 1
[Link](90); // size → 2
[Link](78); // size → 3
[Link](92); // size → 4 (grows automatically!)
[Link](0); // size → 3 (shrinks automatically!)
SECTION 03 — The add() Method — Append & Insert

The add() method is used to insert new elements into an ArrayList. There are two forms, and
knowing the difference between them is essential.

[Link](element) [Link](index, element)


Appends the element to the end of the list. Size Inserts the element at the specified index. All
increases by 1. This is the most commonly used elements at that index and beyond shift one
form. position to the right. Size increases by 1.
Time: O(1) amortised Index must be 0 to [Link]() inclusive.

Example — Appending to the End


Java — add(element)

ArrayList<String> colours = new ArrayList<>();


[Link]("Red"); // ["Red"]
[Link]("Green"); // ["Red", "Green"]
[Link]("Blue"); // ["Red", "Green", "Blue"]
[Link](colours); // [Red, Green, Blue]
[Link]([Link]()); // 3

Example — Inserting at a Specific Index


Java — add(index, element)

ArrayList<String> fruits = new ArrayList<>();


[Link]("Apple"); // index 0
[Link]("Cherry"); // index 1
[Link]("Date"); // index 2

// Insert "Banana" at index 1:


[Link](1, "Banana");
// Result: ["Apple", "Banana", "Cherry", "Date"]
// 0 1 2 3
// "Cherry" shifted: 1 → 2 | "Date" shifted: 2 → 3

Visual: Index shift after add(1, "Banana")


[0] [1] [2] [3]

Before Apple Cherry Date —


After Apple Banana Cherry Date

■ IndexOutOfBoundsException
Calling add(index, element) with an index below 0 or above [Link]() throws
IndexOutOfBoundsException. Valid insertion indices are 0 to [Link]() inclusive (you may insert at
the very end, which is equivalent to add(element)).
SECTION 04 — The remove() Method — Delete & Shift

The remove(int index) method deletes the element at the given index. All elements to the right
automatically shift one position to the left to fill the gap, and the size decreases by 1. The removed
element is returned.

[Link](index)
Deletes the element at the given index. Elements at higher indices shift left by 1. Size decreases by 1.
Returns the removed element.
Throws IndexOutOfBoundsException if index < 0 or index >= [Link]().

Example — Removing by Index


Java — remove(index)

ArrayList<String> animals = new ArrayList<>();


[Link]("Cat"); // index 0
[Link]("Dog"); // index 1
[Link]("Fish"); // index 2
[Link]("Bird"); // index 3

// Remove element at index 1:


String removed = [Link](1);
[Link](removed); // Dog
[Link](animals); // [Cat, Fish, Bird]
// "Fish" shifted: 2 → 1 | "Bird" shifted: 3 → 2

Visual: Index shift after remove(1)


[0] [1] [2] [3]

Before Cat Dog Fish Bird


After Cat Fish Bird —

■ Common Mistake — Loop + Remove


Never call [Link]() inside a for-each loop — this causes ConcurrentModificationException. Use
a standard for loop iterating backwards, or use an Iterator with its own remove() method.
SECTION 05 — The get() and set() Methods

The get() method reads the value at a given index without modifying the list. The set() method
replaces the value at a given index. Both use zero-based indexing, just like arrays.

[Link](index) [Link](index, element)


Returns the element at the given index. The list is Replaces the element at the given index with the
not modified (non-destructive, read-only). new element. Returns the old element that was
replaced.
First element: index 0. Last: index [Link]() - 1. Index must be 0 to [Link]() - 1 inclusive.

Java — get() and set()

ArrayList<String> days = new ArrayList<>();


[Link]("Mon"); // index 0
[Link]("Tue"); // index 1
[Link]("Wed"); // index 2
[Link]("Thu"); // index 3

// get() — read without modifying


String d = [Link](2); // d = "Wed"
[Link](days); // [Mon, Tue, Wed, Thu] — UNCHANGED

// set() — replace value at index 1


String old = [Link](1, "Tuesday");
[Link](old); // Tue (the replaced value)
[Link](days); // [Mon, Tuesday, Wed, Thu]

✦ Key Distinction — Destructive vs Non-Destructive get() is non-destructive: it only reads the


value, the list is unchanged. remove() is destructive: it deletes the element, changes the size,
and shifts indices. set() is replacement: it changes a value but keeps the same size and indices.
SECTION 06 — The size() Method

The size() method returns the current number of elements in the ArrayList as an int. Unlike an
array's .length property, size() updates dynamically every time you add or remove an element.
Java — size()

ArrayList<Integer> nums = new ArrayList<>();


[Link]([Link]()); // 0 (empty list)

[Link](10);
[Link](20);
[Link](30);
[Link]([Link]()); // 3

[Link](0);
[Link]([Link]()); // 2 (shrinks after remove)

// Key difference from arrays:


int[] arr = new int[5]; // [Link] is always 5
// [Link]() varies — it is always accurate

■ Golden Rule — Loop Condition


Always write i < [Link]() as your loop condition. Never write i <= [Link]() — this causes
IndexOutOfBoundsException on the final iteration because valid indices run from 0 to size() - 1
only. Also never hardcode a number like i < 5 — always use size() so the loop adapts if the list
changes.

Property Arrays ArrayLists


How to check count [Link] [Link]()
Syntax type Property — no parentheses Method call — parentheses required
Changes over time? No — always equals declared Yes — updates on every add/remove
size
Empty check [Link] == 0 [Link]() or [Link]() == 0
SECTION 07 — Traversal — Looping Through a List

Traversal means visiting every element of an ArrayList in order. The IBDP syllabus requires you to
know all three approaches. Choosing the correct one depends on whether you need the index, and
whether you are modifying the list during iteration.

Method Syntax When to use


for-each loop for (Type x : list) {} Recommended. When you only need the
(Enhanced for) value, not the index.
Standard for loop + for (int i=0; i<[Link](); i++) When you need the index alongside the value,
get() or when using set().
Iterator Iterator it = [Link](); When you need to safely remove elements
while([Link]()){ [Link](); during iteration.
}

Method 1 — for-each (Enhanced for)


Java — for-each

ArrayList<String> names = new ArrayList<>();


[Link]("Alice"); [Link]("Bob"); [Link]("Charlie");

for (String name : names) { // type must match list's generic type
[Link](name);
}
// Output:
// Alice
// Bob
// Charlie

Method 2 — Standard for Loop with get()


Java — for loop

for (int i = 0; i < [Link](); i++) { // NOT i <= [Link]()


[Link](i + ": " + [Link](i));
}
// Output:
// 0: Alice
// 1: Bob
// 2: Charlie

Method 3 — Iterator (Safe Removal)


Java — Iterator

import [Link];
Iterator<String> it = [Link]();
while ([Link]()) {
String n = [Link]();
if ([Link]("Bob")) {
[Link](); // safe! Does NOT throw exception
}
}
[Link](names); // [Alice, Charlie]

Worked Example — Finding the Maximum


A classic traversal pattern: initialise a variable with the first element, then loop from index 1,
updating whenever a larger value is found.
Java — Find Maximum

ArrayList<Integer> temps = new ArrayList<>();


[Link](31); [Link](27); [Link](35); [Link](29);

int max = [Link](0); // start with first element


for (int i = 1; i < [Link](); i++) {
if ([Link](i) > max) {
max = [Link](i);
}
}
[Link]("Max temperature: " + max); // 35
SECTION 08 — Worked Examples — Complete Programs

Example 1 — Sum and Average of Scores


Java — Sum & Average

import [Link];
public class SumAverage {
public static void main(String[] args) {
ArrayList<Integer> scores = new ArrayList<>();
[Link](72); [Link](85); [Link](90);
[Link](60); [Link](78);

int sum = 0;
for (int score : scores) {
sum += score;
}
// Cast to double to avoid integer division truncation
double average = (double) sum / [Link]();
[Link]("Sum: " + sum);
[Link]("Average: " + average);
}
}
// Output:
// Sum: 485
// Average: 97.0

Example 2 — Linear Search


Java — Linear Search

import [Link];
import [Link];
public class LinearSearch {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
[Link]("Mumbai"); [Link]("Delhi");
[Link]("Pune"); [Link]("Chennai");

Scanner sc = new Scanner([Link]);


[Link]("Search for: ");
String target = [Link]();

boolean found = false;


for (int i = 0; i < [Link](); i++) {
if ([Link](i).equals(target)) { // use .equals() not ==
[Link](target + " found at index " + i);
found = true;
break;
}
}
if (!found) [Link](target + " not found.");
}
}
// Output: Pune found at index 2
Example 3 — Parallel Lists (Student Grade Manager)
Two ArrayLists at the same index always refer to the same student. This is the most common way
to associate names with values in SL.
Java — Parallel Lists

import [Link];
public class GradeManager {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();

[Link]("Aanya"); [Link](88);
[Link]("Rohan"); [Link](72);
[Link]("Priya"); [Link](95);
[Link]("Arjun"); [Link](60);

// Find top scorer — track INDEX, not just max value


int maxIdx = 0;
for (int i = 1; i < [Link](); i++) {
if ([Link](i) > [Link](maxIdx)) maxIdx = i;
}
[Link]("Top: " + [Link](maxIdx)
+ " (" + [Link](maxIdx) + ")");
}
}
// Output: Top: Priya (95)
SECTION 09 — 2D ArrayLists

A 2D ArrayList is an ArrayList whose elements are themselves ArrayLists — an 'ArrayList of


ArrayLists'. This creates a table or grid structure where rows can have different lengths (unlike a 2D
array).
Java — 2D ArrayList

import [Link];

// Declare: ArrayList of ArrayLists


ArrayList<ArrayList<Integer>> table = new ArrayList<>();

// Create and add row 0: [10, 20, 30]


ArrayList<Integer> row0 = new ArrayList<>();
[Link](10); [Link](20); [Link](30);
[Link](row0);

// Create and add row 1: [40, 50, 60]


ArrayList<Integer> row1 = new ArrayList<>();
[Link](40); [Link](50); [Link](60);
[Link](row1);

// Access element at row 1, column 2:


int val = [Link](1).get(2); // val = 60

// Traverse the 2D structure:


for (int r = 0; r < [Link](); r++) {
for (int c = 0; c < [Link](r).size(); c++) {
[Link]([Link](r).get(c) + " ");
}
[Link](); // new line after each row
}
// Output:
// 10 20 30
// 40 50 60

✦ Why Use 2D ArrayList over 2D Array? Each row can have a different number of columns
(jagged structure). Rows and columns can be added or removed at runtime. The inner and outer
sizes are both dynamic. Ideal for variable-size grids, game boards, or student-subject records.
SECTION 10 — Common Errors & Exam Tips

Common Errors
IndexOutOfBoundsException
Using i <= [Link]() instead of i < [Link]() in a loop. Valid indices are 0 to size()-1. The last index
is NOT size().
ArrayList<int> — compile error
Generics require reference types. Write ArrayList<Integer> not ArrayList<int>. Use wrapper:
Integer, Double, Boolean, Character.
Missing import
Forgetting import [Link]; at the top. Causes compilation error.
.length vs .size()
Arrays use .length (no parentheses, a field). ArrayLists use .size() (parentheses, a method call).
Mixing them is a common exam error.
ConcurrentModificationException
Calling [Link]() inside a for-each loop. Use Iterator with [Link]() or a backwards for loop
instead.
== vs .equals() for Strings
Never use == to compare String content — it checks reference, not value. Always use .equals()
when comparing String objects.
SECTION 11 — Quick Reference Summary

This table summarises all ArrayList methods you need for IBDP Computer Science SL. Learn the
method signatures, what they return, and potential exceptions.

Method Syntax Returns Notes / Exception


[Link](e) void Appends; size +1
[Link](i, e) void Shifts right; IndexOutOfBoundsException if i < 0 or i
> size()
[Link](i) removed Shifts left; IndexOutOfBoundsException if i < 0 or i
element >= size()
[Link](i) element at i Non-destructive; IndexOutOfBoundsException if
invalid index
[Link](i, e) old element Size unchanged; IndexOutOfBoundsException if
invalid index
[Link]() int Updates on every add/remove
[Link]() boolean Returns true if size() == 0
[Link](e) boolean Linear search O(n)
[Link](e) int Returns -1 if not found
[Link]() void Empties list; size becomes 0
[Link]() Iterator Use [Link]() and [Link]()

You might also like