Skillversitas

Array & ArrayList

An Array in Java is a fixed-size data structure that stores elements of the same type. The size of an array is determined at creation and cannot be changed. ArrayList from java.util is the dynamic alternative that can grow and shrink as needed, similar to lists in Python.

Arrays are more efficient in terms of memory and access performance (direct indexing), but their flexibility is limited. ArrayList uses an internal array that is automatically resized when its capacity runs out (minimal overhead). Both support index-based access, iteration, and searching.

Java provides the Arrays utility class for array operations: Arrays.sort(), Arrays.toString(), Arrays.copyOf(), Arrays.fill(), Arrays.binarySearch(). To iterate over an array, use the more compact and safer for-each loop.

Array vs ArrayList:

Feature Array ArrayList
Size Fixed Dynamic
Type Primitives & objects Objects only
Access arr[i] list.get(i)
Add Not possible list.add(e)
Remove Not possible list.remove(i)
Utility Arrays.sort() Collections.sort()

Code Example

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayDanArrayList {
    public static void main(String[] args) {
        // Static array
        int[] numbers = {10, 20, 30, 40, 50};
        for (int a : numbers) {
            System.out.print(a + " ");
        }
        System.out.println();

        // Array with a specific length
        String[] name = new String[3];
        name[0] = "John";
        name[1] = "Anna";
        name[2] = "Sarah";
        System.out.println("Array: " + Arrays.toString(name));

        // ArrayList (dynamic)
        ArrayList<String> city = new ArrayList<>();
        city.add("New York");
        city.add("Chicago");
        city.add("Boston");
        city.add(1, "Austin"); // insert at index 1
        System.out.println("ArrayList: " + city);

        // Remove and access
        city.remove("New York");
        System.out.println("After removal: " + city);
        System.out.println("Element at index 0: " + city.get(0));

        // Sort an array
        int[] unsorted = {5, 2, 8, 1, 9};
        Arrays.sort(unsorted);
        System.out.println("Sorted: " + Arrays.toString(unsorted));
    }
}

Code Explanation

  1. Static array: int[] numbers = {10, 20, ...} — declaration and initialization in a single line. The length is accessed with .length.
  2. Array with a length: new String[3] creates an array with 3 null elements, which is then filled in one by one.
  3. ArrayList: new ArrayList<>() creates an empty list. add() appends an element at the end, and add(index, element) inserts at a specific position. remove() removes an element. get(i) retrieves an element by index.
  4. Arrays utility: Arrays.sort() sorts an array. Arrays.toString() converts an array into a readable string.

Everyday Example

A shopping list management program using ArrayList:

import java.util.ArrayList;
import java.util.Scanner;

public class ShoppingList {
    public static void main(String[] args) {
        ArrayList<String> shoppingList = new ArrayList<>();
        shoppingList.add("Rice 5kg");
        shoppingList.add("Cooking oil");
        shoppingList.add("Eggs 1kg");
        shoppingList.add("Sugar 1kg");

        System.out.println("=== Shopping List ===");
        int no = 1;
        for (String item : shoppingList) {
            System.out.println(no + ". " + item);
            no++;
        }

        // Add a new item
        shoppingList.add("UHT Milk");
        System.out.println("\nAfter adding: " + shoppingList.size() + " items");

        // Remove the first item
        String removed = shoppingList.remove(0);
        System.out.println("Removed: " + removed);
        System.out.println("Remaining: " + shoppingList);
    }
}

Summary

Arrays are a good fit for fixed-size data with maximum performance. ArrayLists are a good fit for dynamic data that is frequently added to or removed from. The Java Collections Framework provides many other data structures such as LinkedList, HashSet, and HashMap, which will be covered in the next chapter.