Mastering Java ArrayLists and Building a Student Record System

Introduction to Dynamic Arrays

The ArrayList class in Java offers a dynamic array implementation capable of resizing automatically as element are added or removed. Unlike traditional arrays where the capacity is fixed upon instantiation, an ArrayList expands its internal storage as needed.

Core Differences: Array vs. Collection

Feature Array ArrayList
Capacity Fixed size at creation Dynamic, grows automatically
Type Safety Strong (primitive or reference) Ganeric (<E>)
Operations Manual bounds manaegment Built-in add/remove/index methods

Initialization and Insertion

To utilize generics, specify the type parameter using angle brackets (e.g., <String> or <Student>). The E placeholder represents any specific data type required.

// Basic instantiation
List<String> stringList = new ArrayList<>();

// Appending elements to the end
stringList.add("Element A");
stringList.add("Element B");

// Inserting at a specific position
stringList.add(1, "Inserted Item");

Common Manipulation Methods

Method Signature Description
boolean add(E e) Appends element to the tail. Returns true on success.
void add(int index, E element) Inserts element at the given index. Shifts subsequent elements.
E remove(int index) Removes element at index and returns it. Throws exception if invalid index.
boolean remove(Object o) Removes first occurrence of object. Returns true if modified.
E set(int index, E element) Replaces element at index. Returns previous value.
E get(int index) Retrieves element at specified index.
int size() Returns total count of elements.

Practical Application Scenarios

1. Traversing String Collections

Iterating through a list requires accessing each element via its index and checking the total length.

public void traverseStrings() {
    List<String> records = new ArrayList<>();
    records.add("Alice");
    records.add("Bob");
    records.add("Charlie");

    for (int i = 0; i < records.size(); i++) {
        System.out.println(records.get(i));
    }
}

2. Managing Custom Objects

Collections can store complex objects. Ensure the class has appropriate getters/setters.

public void manageObjects() {
    List<Person> roster = new ArrayList<>();
    
    roster.add(new Person("John Doe", 25));
    roster.add(new Person("Jane Smith", 30));
    
    // Display details using iteration
    for (int i = 0; i < roster.size(); i++) {
        Person p = roster.get(i);
        System.out.println(p.getName() + " | Age: " + p.getAge());
    }
}

// Simplified Domain Class
class Person {
    private String name;
    private int age;

    public Person(String n, int a) { this.name = n; this.age = a; }
    public String getName() { return name; }
    public int getAge() { return age; }
}

3. Interactive Data Entry

For user-driven applications, combine collections with Scanner to capture runtime input.

public void collectInput(List<Person> targetList) {
    Scanner console = new Scanner(System.in);
    
    System.out.print("Enter Name: ");
    String n = console.nextLine();
    
    System.out.print("Enter Age: ");
    int a = Integer.parseInt(console.nextLine());
    
    Person entry = new Person(n, a);
    targetList.add(entry);
}

Full Implementation: Student Database CLI

This section details a complete command-line interface (CLI) application demonstrating CRUD (Create, Read, Update, Delete) operations.

1. Domain Model Definition

The Student class encapsulates attributes and provides accessors.

package app.model;

public class StudentRecord {
    private String enrollmentId;
    private String fullName;
    private int yearsOfAge;
    private String birthDate;

    public StudentRecord() {}

    public StudentRecord(String id, String name, int age, String dob) {
        this.enrollmentId = id;
        this.fullName = name;
        this.yearsOfAge = age;
        this.birthDate = dob;
    }

    public String getEnrollmentId() { return enrollmentId; }
    public void setEnrollmentId(String id) { this.enrollmentId = id; }
    
    public String getFullName() { return fullName; }
    public void setFullName(String name) { this.fullName = name; }
    
    public int getYearsOfAge() { return yearsOfAge; }
    public void setYearsOfAge(int age) { this.yearsOfAge = age; }
    
    public String getBirthDate() { return birthDate; }
    public void setBirthDate(String dob) { this.birthDate = dob; }
}

2. System Controller Logic

The main controller manages the menu loop and delegates tasks to helper methods.

package app.core;

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

public class CampusSystem {
    private final List<StudentRecord> database;
    private final Scanner scanner;

    public CampusSystem() {
        this.database = new ArrayList<>();
        this.scanner = new Scanner(System.in);
    }

    public void run() {
        while (true) {
            printMenu();
            String choice = scanner.nextLine();

            switch (choice) {
                case "1": addStudent(); break;
                case "2": removeStudent(); break;
                case "3": updateStudent(); break;
                case "4": displayRecords(); break;
                case "5": System.exit(0);
                default: System.out.println("Invalid selection.");
            }
        }
    }

    private void printMenu() {
        System.out.println("\n=== MAIN MENU ===");
        System.out.println("1. Register New Student");
        System.out.println("2. Remove Student");
        System.out.println("3. Modify Student Details");
        System.out.println("4. View All Records");
        System.out.println("5. Quit System");
        System.out.print("Select Option: ");
    }

    // Retrieve index by ID
    private int findRecordIndex(String id) {
        int foundIndex = -1;
        for (int i = 0; i < database.size(); i++) {
            if (database.get(i).getEnrollmentId().equals(id)) {
                foundIndex = i;
                break;
            }
        }
        return foundIndex;
    }

    private void addStudent() {
        System.out.print("Enter Unique ID: ");
        String id = scanner.nextLine();

        if (findRecordIndex(id) != -1) {
            System.out.println("ID exists already.");
            return;
        }

        System.out.print("Enter Full Name: ");
        String name = scanner.nextLine();
        System.out.print("Enter Age: ");
        int age = Integer.parseInt(scanner.nextLine());
        System.out.print("Enter Birth Date: ");
        String dob = scanner.nextLine();

        database.add(new StudentRecord(id, name, age, dob));
        System.out.println("Registration Successful.");
    }

    private void removeStudent() {
        System.out.print("Enter ID to Delete: ");
        String id = scanner.nextLine();
        int idx = findRecordIndex(id);

        if (idx == -1) {
            System.out.println("ID not found.");
        } else {
            database.remove(idx);
            System.out.println("Deletion Complete.");
        }
    }

    private void updateStudent() {
        System.out.print("Enter ID to Update: ");
        String id = scanner.nextLine();
        int idx = findRecordIndex(id);

        if (idx == -1) {
            System.out.println("No record matches that ID.");
        } else {
            System.out.print("New Name: ");
            String newName = scanner.nextLine();
            System.out.print("New Age: ");
            int newAge = Integer.parseInt(scanner.nextLine());
            System.out.print("New DOB: ");
            String newDob = scanner.nextLine();

            StudentRecord updated = new StudentRecord(
                id, newName, newAge, newDob
            );
            database.set(idx, updated);
            System.out.println("Update Confirmed.");
        }
    }

    private void displayRecords() {
        if (database.isEmpty()) {
            System.out.println("Database is empty.");
            return;
        }
        System.out.printf("%-15s %-20s %-10s %-15s%n", "ID", "Name", "Age", "DOB");
        System.out.println("------------------------------------------------");
        for (StudentRecord s : database) {
            System.out.printf("%-15s %-20s %-10d %-15s%n", 
                s.getEnrollmentId(), s.getFullName(), s.getYearsOfAge(), s.getBirthDate());
        }
    }

    public static void main(String[] args) {
        new CampusSystem().run();
    }
}

Tags: java Collections ArrayList OOP CLI

Posted on Fri, 15 May 2026 21:44:56 +0000 by izy