AP Computer Science A

Advanced Placement Computer Science A focusing on Java programming and object-oriented design.

Advanced Topics

Arrays and ArrayLists

Organizing Data: Arrays and ArrayLists

When you need to work with lots of data, like a list of students or scores, you use arrays and ArrayLists in Java.

Arrays

An array is a fixed-size container for items of the same type.

int[] scores = {95, 87, 74, 100};
System.out.println(scores[2]); // 74

Arrays are fast and simple, but their size can't change after creation.

ArrayLists

An ArrayList is like a growable array—useful when you don't know how much data you'll have.

import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names.get(0)); // Alice

When to Use Which

  • Use arrays for fixed-size collections.
  • Use ArrayLists for flexible, changing data.

Real-World Examples

  • Storing high scores in a game.
  • Managing a list of friends in a social network app.

Quick Tips

  • Arrays: scores.length
  • ArrayLists: names.size()

Examples

  • Keeping track of inventory items in a store using an ArrayList.

  • Recording daily temperatures in an array for a weather app.

In a Nutshell

Arrays and ArrayLists help you store and manage collections of data efficiently in Java.