Java ArrayList Class


ArrayList represents a resizable array which belongs to the java.util package. ArrayList stands out from standard Java arrays by allowing dynamic resizing which makes it a more adaptable choice for handling object lists.


Key Features

  • Dynamic resizing
  • Maintains insertion order
  • Allows duplicate elements
  • Non-synchronized (not thread-safe by default)

Syntax

ArrayList list = new ArrayList();
 

Example

ArrayList names = new ArrayList(); 

Methods and Examples

Adding Elements

names.add("Alice");
names.add("Bob");
names.add("Charlie");
 

Accessing Elements

 System.out.println(names.get(0));

Changing Elements

names.set(1, "Brian"); 

Size of ArrayList

 System.out.println(names.size()); 

Example

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList fruits = new ArrayList<>();

        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        // Print all elements
        for(String fruit : fruits) {
            System.out.println(fruit);
        }

        // Modify element
        fruits.set(1, "Grapes");

        // Remove element
        fruits.remove("Apple");

        // Check contents
        System.out.println("List contains Mango: " + fruits.contains("Mango"));
        System.out.println("Final list: " + fruits);
    }
}

notepad

ArrayList stores objects exclusively while primitive types need to be wrapped in their corresponding wrapper classes like Integer, Double, etc.

Not thread-safe. Use Collections.synchronizedList() or CopyOnWriteArrayList for thread safety.




Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.