Unit 7: ArrayList

This unit covers ArrayList creation, manipulation, and common ArrayList operations in Java programming.

Key Concepts

  • ArrayList Creation: Creating and initializing ArrayLists
  • ArrayList Methods: add(), remove(), get(), set(), size()
  • ArrayList Traversal: Iterating through ArrayLists
  • ArrayList vs Array: Understanding the differences
  • ArrayList Algorithms: Searching and sorting
  • ArrayList as Parameters: Passing ArrayLists to methods
  • ArrayList of Objects: Working with custom classes

Example Code


// Example: Working with ArrayList in Java
import java.util.ArrayList;

public class ArrayListExamples {
  public static void main(String[] args) {
    // ArrayList creation
    ArrayList names = new ArrayList<>();
    ArrayList numbers = new ArrayList<>();
    
    // Adding elements
    names.add("Alice");
    names.add("Bob");
    names.add("Charlie");
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    
    // ArrayList traversal
    System.out.println("Names ArrayList:");
    for (int i = 0; i < names.size(); i++) {
      System.out.println("Index " + i + ": " + names.get(i));
    }
    
    // Enhanced for loop
    System.out.println("\nNumbers ArrayList:");
    for (Integer num : numbers) {
      System.out.println(num);
    }
    
    // ArrayList methods
    System.out.println("\nArrayList Operations:");
    System.out.println("Size: " + names.size());
    System.out.println("Contains 'Bob': " + names.contains("Bob"));
    System.out.println("Index of 'Charlie': " + names.indexOf("Charlie"));
    
    // Modifying elements
    names.set(1, "Robert");
    System.out.println("\nAfter modification:");
    System.out.println(names);
    
    // Removing elements
    names.remove("Charlie");
    System.out.println("\nAfter removal:");
    System.out.println(names);
    
    // ArrayList of custom objects
    ArrayList students = new ArrayList<>();
    students.add(new Student("Alice", 95));
    students.add(new Student("Bob", 88));
    
    // Sorting ArrayList
    System.out.println("\nStudents before sorting:");
    for (Student student : students) {
      System.out.println(student);
    }
    
    // Sort by grade (assuming Student class implements Comparable)
    java.util.Collections.sort(students);
    
    System.out.println("\nStudents after sorting:");
    for (Student student : students) {
      System.out.println(student);
    }
  }
}

// Student class for ArrayList example
class Student implements Comparable {
  private String name;
  private int grade;
  
  public Student(String name, int grade) {
    this.name = name;
    this.grade = grade;
  }
  
  @Override
  public int compareTo(Student other) {
    return Integer.compare(this.grade, other.grade);
  }
  
  @Override
  public String toString() {
    return name + " (" + grade + ")";
  }
}
              

Interactive Code Playground

Try out your own ArrayList code here! The code will run in a safe environment.

Output:

            

Practice Problems

  1. Write a program that removes all duplicates from an ArrayList.
  2. Implement a method that reverses an ArrayList without using Collections.reverse().
  3. Create a program that merges two sorted ArrayLists into a single sorted ArrayList.

Tips for Success

  • Remember to import java.util.ArrayList.
  • Use size() instead of length for ArrayList size.
  • Be careful when removing elements during iteration.
  • Use appropriate ArrayList methods instead of array operations.
  • Consider using enhanced for loops when possible.

Test Your Knowledge

1. What is the correct way to create an ArrayList of integers?
ArrayList numbers = new ArrayList<>();
ArrayList numbers = new ArrayList<>();
ArrayList numbers = new ArrayList();
ArrayList numbers = new ArrayList();
The correct answer is B. ArrayList numbers = new ArrayList<>();. ArrayLists can only store objects, so we must use the wrapper class Integer instead of the primitive type int.
2. What happens when you try to add an element to an ArrayList that is already at its capacity?
The ArrayList throws an IndexOutOfBoundsException
The ArrayList automatically resizes itself
The ArrayList deletes the last element
The ArrayList becomes read-only
The correct answer is B. The ArrayList automatically resizes itself. ArrayLists are dynamic and will automatically increase their capacity when needed.
3. What is the difference between ArrayList.remove(index) and ArrayList.remove(Object)?
remove(index) removes by position, remove(Object) removes by value
remove(index) is faster than remove(Object)
remove(index) returns void, remove(Object) returns boolean
There is no difference
The correct answer is A. remove(index) removes the element at the specified position, while remove(Object) removes the first occurrence of the specified element from the ArrayList.

The Comparable Interface

The Comparable interface is used to define a natural ordering for objects. It's particularly useful when you need to sort objects in a collection.

Key Points:

  • The Comparable interface is part of the java.lang package
  • It requires implementing the compareTo method
  • The compareTo method returns:
    • A negative integer if the current object is less than the argument
    • Zero if the current object is equal to the argument
    • A positive integer if the current object is greater than the argument
  • It's used by Collections.sort() to sort objects

Example: Student Class with Multiple Comparison Strategies


// Student class implementing Comparable
public class Student implements Comparable {
    private String name;
    private int grade;
    private double gpa;
    
    public Student(String name, int grade, double gpa) {
        this.name = name;
        this.grade = grade;
        this.gpa = gpa;
    }
    
    // Natural ordering by grade
    @Override
    public int compareTo(Student other) {
        return Integer.compare(this.grade, other.grade);
    }
    
    // Alternative comparison by GPA
    public int compareByGPA(Student other) {
        return Double.compare(this.gpa, other.gpa);
    }
    
    // Alternative comparison by name
    public int compareByName(Student other) {
        return this.name.compareTo(other.name);
    }
    
    @Override
    public String toString() {
        return name + " (Grade: " + grade + ", GPA: " + gpa + ")";
    }
}
              

Practice Problems:

  1. Create a Book class that implements Comparable to sort books by title.
  2. Modify the Student class to sort by GPA when grades are equal.
  3. Create a Rectangle class that implements Comparable to sort by area.
  4. Implement a Date class that can be sorted chronologically.
  5. Create a Person class that can be sorted by age, then by name if ages are equal.

Tips for Success:

  • Always implement compareTo consistently with equals
  • Use the appropriate wrapper class's compare method for primitive types
  • Consider multiple fields when implementing natural ordering
  • Remember that compareTo should throw NullPointerException if the argument is null
  • Use Comparator when you need multiple sorting strategies