Java ArrayList.size(): Getting Element Count & Managing Loop Bounds

The ArrayList.size() method returns the exact number of elements currently stored in the list as an int in O(1) constant time.

Related List Operations: Because ArrayList uses 0-based indexing, valid indices for ArrayList.get() and ArrayList.set() always run from 0 to size() - 1. To test whether size() == 0, prefer ArrayList.isEmpty(). To manage the underlying buffer capacity separately from size(), see ArrayList.ensureCapacity() and ArrayList.trimToSize().

1. Syntax, Method Signature & Constant-Time Lookup 🔝

Declared in java.util.ArrayList<E> (implementing Collection.size()):

 // Returns the number of elements currently stored in this list
public int size()
Aspect Specification Operational Rule
Return Value int (>= 0) Number of elements currently present in the list (including duplicates and nulls).
Time Complexity O(1) Returns the private int size counter directly without scanning the array.
Last Element Index size() - 1 When size() > 0, the final element is always at list.get(list.size() - 1).

2. Basic Element Counting & For-Loop Traversal 🔝

Combining size() with a for loop and get(i) visits every element from index 0 up to size() - 1:

ArrayList<Integer> marks = new ArrayList<Integer>(Arrays.asList(55, 54, 55, 54));
System.out.println("Total marks count: " + marks.size());  // 4

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "Python"));

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

Terminal Output:

Total marks count: 4
Java
PHP
Python

3. How Mutation Methods Affect size() 🔝

add() and addAll() increment size(), remove() and clear() decrement or reset size(), while set(index, val) overwrites an existing slot and leaves size() unchanged:

ArrayList<String> list = new ArrayList<>();
System.out.println("Initial size:     " + list.size());  // 0

list.add("A");
list.add("B");
System.out.println("After 2 adds:     " + list.size());  // 2

list.set(0, "A-Updated");
System.out.println("After set(0, ..): " + list.size());  // 2

list.remove(1);
System.out.println("After remove(1):  " + list.size());  // 1

Terminal Output:

Initial size:     0
After 2 adds:     2
After set(0, ..): 2
After remove(1):  1

4. Logical size() vs Backing Capacity & Null Elements 🔝

Do not confuse size() with internal array capacity! Creating new ArrayList<>(50) allocates room for 50 items, but size() is still 0. Conversely, adding a null reference via items.add(null) does count as an element and increments size():

ArrayList<String> items = new ArrayList<>(50);
System.out.println("New with capacity 50 -> size(): " + items.size());  // 0

items.add(null);
items.add("Data");
System.out.println("After adding null + 'Data' -> size(): " + items.size());  // 2

Terminal Output:

New with capacity 50 -> size(): 0
After adding null + 'Data' -> size(): 2

5. Java's Three Length Idioms: length vs length() vs size() 🔝

One of the most frequent compiler errors for Java developers is mixing up how arrays, strings, and collections report their size:

int[] rawArray = {10, 20, 30};
String text = "Java";
ArrayList<String> list = new ArrayList<>(Arrays.asList("X", "Y"));

System.out.println("int[].length:     " + rawArray.length);  // Field (no parentheses)
System.out.println("String.length():  " + text.length());    // Method: length()
System.out.println("ArrayList.size(): " + list.size());      // Method: size()

Terminal Output:

int[].length:     3
String.length():  4
ArrayList.size(): 2

6. Comparison: Sizing & Capacity Methods Across Java Types 🔝

Quick reference across arrays, strings, and ArrayList:

Target Type Syntax What It Returns
ArrayList<E> / Collection list.size() Number of logical elements currently stored in the collection.
Java Array (T[], int[]) arr.length Fixed total slot capacity of the array (field, no parentheses).
String / CharSequence str.length() Number of char code units in the string.

7. Production Recipe: Paginating an ArrayList Using size() & subList() 🔝

Using Math.min(start + pageSize, ids.size()) with subList() slices a list into safe pages without overflowing the final partial page:

public class ListPaginator {
    public static void main(String[] args) {
        ArrayList<Integer> ids = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        int pageSize = 2;
        for (int start = 0; start < ids.size(); start += pageSize) {
            int end = Math.min(start + pageSize, ids.size());
            System.out.println("Page: " + ids.subList(start, end));
        }
    }
}

Terminal Output:

Page: [1, 2]
Page: [3, 4]
Page: [5]

8. Practical Recipe: Reverse Traversal from size() - 1 for Safe Deletion 🔝

Starting a loop at i = scores.size() - 1 and decrementing down to 0 allows you to call scores.remove(i) safely without skipping adjacent elements when indices shift:

public class ReverseLoopRemoval {
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>(Arrays.asList(40, 85, 30, 95));
        for (int i = scores.size() - 1; i >= 0; i--) {
            if (scores.get(i) < 50) scores.remove(i);
        }
        System.out.println("Passing scores: " + scores);
    }
}

Terminal Output:

Passing scores: [85, 95]

9. Common Developer Pitfalls & Traps 🔝

Off-By-One Loop Condition: i <= list.size()

Writing for (int i = 0; i <= list.size(); i++) runs one iteration too far and crashes with IndexOutOfBoundsException when list.get(list.size()) is called. Always use strict less-than: i < list.size().

Caching int n = list.size() Before a Loop That Mutates the List

If your loop adds or removes elements, a cached variable int n = list.size(); becomes stale immediately! Either evaluate list.size() dynamically in the loop condition or iterate backward.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListSizeFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(20);
        if (list.size() == 0 && list.isEmpty()) {
            System.out.println("Check 1 Passed: Pre-sized list starts with size() == 0.");
        }
        list.addAll(Arrays.asList("One", "Two", "Three"));
        if (list.size() == 3 && list.get(list.size() - 1).equals("Three")) {
            System.out.println("Check 2 Passed: Last index is size() - 1 (2).");
        }
        System.out.println("All ArrayList.size() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: Pre-sized list starts with size() == 0.
Check 2 Passed: Last index is size() - 1 (2).
All ArrayList.size() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Does calling list.size() in a for-loop condition slow down the loop?

No. Because ArrayList.size() simply returns a field (return size;), the JVM JIT compiler inlines the method call completely at zero overhead.

Can ArrayList.size() ever return a negative number?

No. The minimum return value of size() is 0 (when isEmpty() is true).

Does trimToSize() change the value returned by size()?

No. trimToSize() only shrinks the hidden backing array capacity down to match the current size(); the logical element count stays identical.

How do I get the total count of elements in a 2D ArrayList<ArrayList<String>>?

grid.size() returns the number of rows. To count all cells across all rows, sum row.size() for each inner list.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer