Java•ArrayList & Arrays
Java ArrayList and Arrays: Dynamic Collections vs Fixed Arrays
Learn differences between fixed-size primitive arrays and dynamic resizable ArrayList collections.
Syntax
ArrayList<String> list = new ArrayList<>();
list.add("Item");
String val = list.get(0);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| ArrayList<T> | Generic Collection | Resizable array implementation of List interface. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Java locally:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
// Adding elements dynamically
languages.add("Java");
languages.add("Python");
languages.add("Rust");
languages.add("C++");
System.out.println("Initial List: " + languages);
System.out.println("Size: " + languages.size());
System.out.println("Item at 0: " + languages.get(0));
// Sorting collection
Collections.sort(languages);
System.out.println("Sorted List: " + languages);
}
}Expected Output:
Initial List: [Java, Python, Rust, C++] Size: 4 Item at 0: Java Sorted List: [C++, Java, Python, Rust]
How It Works: Step-by-Step
- Lines 5-11: Initializes ArrayList and dynamically adds elements.
- Lines 14: Accesses elements with get(0) and checks size with size().
- Line 17: Sorts list alphabetically with Collections.sort().
Key Concepts
- ArrayList resizes dynamically as elements are added.
- ArrayList only holds Objects; primitives are autoboxed (int -> Integer).
- Arrays (int[]) have fixed size; ArrayList has dynamic capacity.
Common Mistake: Using primitive types as generics: ArrayList<int>
Java generics do not support primitives. Use wrapper classes like ArrayList<Integer>.
❌ Incorrect
ArrayList<int> list = new ArrayList<>(); // Compile Error!
✅ Correct
ArrayList<Integer> list = new ArrayList<>(); // Valid autoboxed wrapper
Related Java Tutorials & Compiler
Java HashMap: Key-Value Mapping and Collections
Store and retrieve key-value pairs using java.util.HashMap with O(1) performance.
Java HashSet: Deduplication and Unique Sets
Store unique collections of elements with java.util.HashSet and set operations.
Java String Methods, StringBuilder, and Immutability
Master String methods (split, substring, replace) and mutable StringBuilder for performance.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.