Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

Java ArrayList: The Stretchy Array

add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

What you will learn

  • Add, insert, read, replace and remove items in an ArrayList
  • Explain why inserting or removing shifts the cells after it
  • Loop over a list and remove items safely with an Iterator or removeIf
  • Tell a fixed List.of list from a growing ArrayList, and how an ArrayList grows

Before you start

  • From arrays to collections: the framework map
  • Java wrapper classes and autoboxing

An ArrayList is a list that grows as you add to it, which is why it's often called the stretchy array. You don't need to memorise its methods (an AI can write the syntax for you), but you do need to know what each one does.

Add to it, read from it

package org.studyeasy.s04l03;

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

public class Ex01_AddAndGet {
    public static void main(String[] args) {
        List<String> courses = new ArrayList<>();
        courses.add("Java");              // goes to the end
        courses.add("SQL");
        courses.add("Spring");
        courses.add(1, "Git");            // squeezes in at index 1

        System.out.println(courses);
        System.out.println("First: " + courses.get(0));
        System.out.println("Size:  " + courses.size());
    }
}
[Java, Git, SQL, Spring]
First: Java
Size:  4

add(value) puts the value at the end; add(1, "Git") squeezes it in at index 1. get(0) reads the first item and size() counts them. This list is for Strings only, so courses.add(42) is an incompatible types error.

Before: Java, SQL, Spring at indexes 0, 1, 2. To add Git at index 1, SQL and Spring each move one cell right, then Git drops into index 1, giving Java, Git, SQL, Spring. JavaSQLSpring JavaGitSQLSpring 012 0123 SQL and Spring shift right to open index 1 get(i) jumps straight to a cell
An insert shifts every cell after it; reading by index is a direct jump.

Change it, search it

List<String> cart = new ArrayList<>();
cart.add("Pen");
cart.add("Notebook");
cart.add("Bag");
cart.add("Ruler");

cart.set(0, "Marker");            // replace what is at index 0
cart.remove(2);                   // remove by index: Bag
cart.remove("Ruler");             // remove by value

System.out.println(cart);
System.out.println("Notebook? " + cart.contains("Notebook"));
System.out.println("Bag?      " + cart.contains("Bag"));
[Marker, Notebook]
Notebook? true
Bag?      false

set overwrites a cell in place. remove works two ways: remove(2) takes out whatever is at index 2 (the Bag) and Ruler moves one cell left; remove("Ruler") finds the value and takes it out. The list closes the gap every time, so there are never holes in the indexes. contains answers true or false. cart.remove(10) throws IndexOutOfBoundsException.

Walk the list two ways

List<Double> prices = new ArrayList<>();
prices.add(12.5);
prices.add(40.0);
prices.add(7.25);

for (int i = 0; i < prices.size(); i++) {    // need the index
    System.out.println("Index " + i + ": " + prices.get(i));
}
double total = 0;
for (double price : prices) {                // just the values
    total += price;
}
System.out.println("Total: " + total);
Index 0: 12.5
Index 1: 40.0
Index 2: 7.25
Total: 59.75

Use the index loop when you need i; use for-each when you only need the values.

Fixed list, growing copy

List<String> weekdays = List.of("Mon", "Tue", "Wed");  // fixed
try {
    weekdays.add("Thu");
} catch (UnsupportedOperationException e) {
    System.out.println("List.of cannot change");
}
List<String> classDays = new ArrayList<>(weekdays);  // a copy
classDays.add("Thu");                                // grows
System.out.println(classDays);
List.of cannot change
[Mon, Tue, Wed, Thu]

List.of gives a fixed list: no add, remove or set. Passing it to new ArrayList<>(...) makes a copy, and the copy can change.

Remove while looping

List<Integer> scores =
        new ArrayList<>(List.of(87, 42, 95, 38, 71));

Iterator<Integer> it = scores.iterator();
while (it.hasNext()) {
    if (it.next() < 50) {
        it.remove();              // the iterator removes it
    }
}
System.out.println("Passed: " + scores);
Passed: [87, 95, 71]

An iterator is like a pointer that starts just before the first value. hasNext checks if there's another, next returns it, and remove deletes the one next just gave you. Calling scores.remove(s) inside a for-each instead makes the loop lose its place, and Java throws ConcurrentModificationException.

The same job in one call is removeIf. It takes a Predicate, an interface with one method that answers true or false for each element, here written as an anonymous class:

scores.removeIf(new Predicate<Integer>() {
    public boolean test(Integer score) {
        return score < 50;        // true = remove it
    }
});

It prints the same Passed: [87, 95, 71]. A lambda makes it shorter still.

An array inside, swapped when full

Inside, an ArrayList holds a plain array. Say it's full: capacity 10, ten names. Add Olivia and there's no free cell, so add calls an internal grow method. It makes a bigger array, the old length plus half of it (10 + 10/2 = 15), copies the ten names across and puts Olivia at index 10. Size is now 11 with four spare cells, and the old array is thrown away. Copying costs time, which is why it adds spare room instead of one cell at a time.

Recap

MethodWhat it does
add(v), add(i, v)at the end, or squeezed in at i
get(i), size()read a cell, count items
set(i, v)replace in place
remove(i), remove(v)by index or by value; the rest move left
contains(v)true or false
Iterator, removeIfremove while looping
List.of(...)fixed; copy into an ArrayList to change it

Next: LinkedList vs ArrayList.

Keep going in Java · 48 of 79

Previous
Java Wrapper Classes and Autoboxing
Next post
Java LinkedList vs ArrayList: Nodes or an Array
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java equals and hashCode: Why a HashSet Needs Both

== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.

From Arrays to Collections: The Java Collections Framework Map

An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.

Java Wrapper Classes and Autoboxing

List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.

Java LinkedList vs ArrayList: Nodes or an Array

An ArrayList is one block of cells; a LinkedList is a chain of nodes with next and prev links. Orders ORD-101 to ORD-106 show addFirst, getLast, removeFirst and remove(1), why get(2) walks two hops, and why a front insert moves three values in one and changes two links in the other.

On this page

  • Add to it, read from it
  • Change it, search it
  • Walk the list two ways
  • Fixed list, growing copy
  • Remove while looping
  • An array inside, swapped when full
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.