Back

Activity 5.10 — ArrayLists

divider

Introduction

Activity 5.10

ArrayLists (Dynamic Lists)

Why ArrayLists exist

  • Arrays work great… until you don’t know how many items you need.
  • ArrayLists can grow and shrink as your program runs.
  • Same indexing idea as arrays, but flexible size.
// Arrays vs ArrayLists (big idea)
// Arrays: fixed size
// ArrayLists: size can change
int[] a = new int[3];
// a.length is always 3
ArrayList<Integer> list = new ArrayList<Integer>();
// list.size() changes as you add/remove

Methods you must know

// ArrayList methods you must know
list.add(value); // append
list.get(index); // read
list.set(index, value);// replace
list.remove(index); // delete by index
list.size(); // current length

Size vs length

  • Arrays use .length
  • ArrayLists use .size()
// Common pitfall
// ArrayList uses .size(), not .length
for (int i = 0; i < list.size(); i++)
{
// ...
}

Wrapper classes

ArrayLists store objects, not primitive types. That’s why we use Integer instead of int.

// Wrapper classes (why Integer, not int?)
ArrayList<int> list; // not allowed
ArrayList<Integer> list; // allowed
// Integer wraps an int so it can be used as an object.

Traversal options

  • Indexed loops are best when you need index positions.
  • For-each loops are best when you only need values.
  • Removing items during traversal needs special care (next activity).

Remove shifts indexes

When you remove an item, items to the right shift left.

// Figure 4 — remove shifts elements left
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
names.add("Ava");
names.add("Ben");
names.add("Chris");
names.remove(1); // removes "Ben"
// Now "Chris" moved to index 1
System.out.println(names);
}
}

Today’s practice

  • Create and modify lists
  • Compute stats from a numeric list
  • Build a dynamic scoreboard using parallel lists
  • Edit a playlist using remove/insert

'F' → Fullscreen

Objectives

  • icon Create and modify ArrayList objects using core methods.
  • icon Traverse ArrayLists using indexed and for-each loops.
  • icon Use parallel ArrayLists to model related data.
  • icon Understand how inserting and removing affects indexing.
divider

Activity Tasks

  • icon Create a new project named Activity5_10_ArrayLists.
  • icon Complete Tasks 1–4.
  • icon Use the figures as references when you get stuck.

Figures: Examples

Figure 1 — Create + add
// Figure 1 — Create an ArrayList and add items
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<String> foods = new ArrayList<String>();
foods.add("pizza");
foods.add("tacos");
foods.add("sushi");
System.out.println(foods);
}
}
Figure 2 — get, set, size
// Figure 2 — get, set, size
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(84);
scores.add(91);
scores.add(76);
System.out.println("First score: " + scores.get(0));
System.out.println("Count: " + scores.size());
scores.set(1, 100); // replace value at index 1
System.out.println(scores);
}
}
Figure 3 — Traversal
// Figure 3 — Traversal (indexed vs for-each)
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(4);
nums.add(7);
nums.add(2);
// Indexed loop (best when you need the index)
for (int i = 0; i < nums.size(); i++)
{
System.out.println(i + ": " + nums.get(i));
}
// For-each loop (best when you only need values)
for (int value : nums)
{
System.out.println(value);
}
}
}
Figure 4 — remove shifts
// Figure 4 — remove shifts elements left
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
names.add("Ava");
names.add("Ben");
names.add("Chris");
names.remove(1); // removes "Ben"
// Now "Chris" moved to index 1
System.out.println(names);
}
}

Task 1: ArrayList Basics (Strings)

Task 1 — Strings list
// Task 1 — ArrayList Basics (Strings)
//
// Create an ArrayList<String> named "movies".
// 1) Add 5 movie titles.
// 2) Print the entire list.
// 3) Print the first movie using get(0).
// 4) Replace the third movie (index 2) with a new title using set.
// 5) Print the list again.
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<String> movies = new ArrayList<String>();
movies.add("The Incredibles");
movies.add("Spider-Man");
movies.add("Toy Story");
movies.add("Shrek");
movies.add("Star Wars");
System.out.println("Movies: " + movies);
System.out.println("First: " + movies.get(0));
movies.set(2, "Finding Nemo");
System.out.println("Updated: " + movies);
}
}

Task 2: Numeric List + Stats

Task 2 — Stats
// Task 2 — Numeric List + Stats
//
// Create an ArrayList<Integer> named "temps".
// 1) Add 7 temperatures (integers).
// 2) Compute and print the average.
// 3) Find and print the max temperature.
// 4) Count and print how many temps are >= 80.
//
// Rules:
// - Use loops (you choose indexed or for-each).
// - Average must be a double.
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<Integer> temps = new ArrayList<Integer>();
temps.add(72);
temps.add(68);
temps.add(75);
temps.add(70);
temps.add(69);
temps.add(82);
temps.add(84);
int sum = 0;
int max = temps.get(0);
int hotCount = 0;
for (int t : temps)
{
sum += t;
if (t > max)
{
max = t;
}
if (t >= 80)
{
hotCount++;
}
}
double avg = (double) sum / temps.size();
System.out.println("Temps: " + temps);
System.out.println("Average: " + avg);
System.out.println("Max: " + max);
System.out.println("Count >= 80: " + hotCount);
}
}

Task 3: Search + Update (Scoreboard)

Task 3 — Parallel ArrayLists
// Task 3 — Search + Update (Dynamic Scoreboard)
//
// Build a "scoreboard" using two parallel ArrayLists:
// - ArrayList<String> names
// - ArrayList<Integer> scores
//
// 1) Add 5 players and their scores (same index = same player).
// 2) Print the scoreboard (name: score).
// 3) Ask the user for a player name.
// - If found, add 10 points to their score.
// - If not found, print "Player not found."
// 4) Print the updated scoreboard.
//
// Hint: use equalsIgnoreCase for name matching.
import java.util.ArrayList;
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
names.add("Ava");
scores.add(40);
names.add("Ben");
scores.add(55);
names.add("Chris");
scores.add(20);
names.add("Dina");
scores.add(65);
names.add("Eli");
scores.add(35);
System.out.println("Scoreboard:");
printScoreboard(names, scores);
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a player name: ");
String target = scanner.nextLine();
int index = findIndex(names, target);
if (index == -1)
{
System.out.println("Player not found.");
}
else
{
scores.set(index, scores.get(index) + 10);
System.out.println("Added 10 points to " + names.get(index) + "!");
}
System.out.println("Updated scoreboard:");
printScoreboard(names, scores);
scanner.close();
}
public static int findIndex(ArrayList<String> names, String target)
{
for (int i = 0; i < names.size(); i++)
{
if (names.get(i).equalsIgnoreCase(target))
{
return i;
}
}
return -1;
}
public static void printScoreboard(ArrayList<String> names, ArrayList<Integer> scores)
{
for (int i = 0; i < names.size(); i++)
{
System.out.println(names.get(i) + ": " + scores.get(i));
}
}
}

Task 4: Remove + Insert (Playlist)

Task 4 — Editing list
// Task 4 — Remove + Insert (Playlist Editor)
//
// Create an ArrayList<String> named "playlist".
// 1) Add 6 song titles.
// 2) Remove the song at index 2.
// 3) Insert a new song at index 0.
// 4) Print the playlist with indexes like:
// 0: SongTitle
// 1: SongTitle
// ...
//
// Hint:
// - playlist.add(index, value) inserts and shifts right
// - playlist.remove(index) removes and shifts left
import java.util.ArrayList;
public class Program
{
public static void main(String[] args)
{
ArrayList<String> playlist = new ArrayList<String>();
playlist.add("Song A");
playlist.add("Song B");
playlist.add("Song C");
playlist.add("Song D");
playlist.add("Song E");
playlist.add("Song F");
playlist.remove(2);
playlist.add(0, "Intro Track");
for (int i = 0; i < playlist.size(); i++)
{
System.out.println(i + ": " + playlist.get(i));
}
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
Movies: [The Incredibles, Spider-Man, Toy Story, Shrek, Star Wars]
First: The Incredibles
Updated: [The Incredibles, Spider-Man, Finding Nemo, Shrek, Star Wars]
Temps: [72, 68, 75, 70, 69, 82, 84]
Average: 74.28571428571429
Max: 84
Count >= 80: 2
Scoreboard:
Ava: 40
Ben: 55
Chris: 20
Dina: 65
Eli: 35
Enter a player name: Ben
Added 10 points to Ben!
Updated scoreboard:
Ava: 40
Ben: 65
Chris: 20
Dina: 65
Eli: 35
0: Intro Track
1: Song A
2: Song B
3: Song D
4: Song E
5: Song F
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Why do ArrayLists use size() instead of length?
  2. What does it mean when we say “remove shifts elements left”?
  3. Why do we use Integer instead of int in an ArrayList?
  4. What is one advantage of an ArrayList over an array?
  5. In Task 3, what does “same index = same record” mean for the two lists?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete