πŸ“Š Java Data Structures
Estimated reading: 3 minutes 31 views

πŸ“š Java ArrayList – Complete Guide with Syntax, Examples & Best Practices


🧲 Introduction – Why Java ArrayList Is a Must-Know Collection

When building Java apps, you often need to store, access, and manipulate dynamic collections of data. That’s where ArrayList comes in β€” a powerful, resizable array from Java’s Collection Framework.

The ArrayList class is widely used because of its simplicity, flexibility, and random-access performance.

By the end of this article, you’ll understand:

βœ… What Java ArrayList is and how it works
βœ… How to declare, initialize, and manipulate ArrayLists
βœ… Key methods like add(), remove(), get(), contains()
βœ… Best practices, performance tips, and real-world use cases


πŸ”‘ What Is ArrayList in Java?

πŸ“š An ArrayList in Java is a resizable array, part of java.util package, which allows duplicate elements and preserves insertion order.

It implements the List interface and supports generics for type safety.


πŸ§ͺ Basic Syntax – Creating an ArrayList

import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>(); // Using Generics
        fruits.add("Apple");
        fruits.add("Banana");
        System.out.println(fruits); // Output: [Apple, Banana]
    }
}

βœ… Explanation:

  • ArrayList<String>: Declares a list of Strings
  • add(): Adds elements to the list
  • Insertion order is preserved

πŸ“¦ Common ArrayList Methods

MethodDescriptionExample
add(E e)Adds element at the endlist.add("Mango")
add(int index, E e)Inserts at specific positionlist.add(1, "Kiwi")
get(int index)Returns element at indexlist.get(0)
set(int index, E e)Replaces element at indexlist.set(1, "Orange")
remove(int index)Removes element at indexlist.remove(0)
contains(Object o)Checks if element existslist.contains("Apple")
indexOf(Object o)Returns index of elementlist.indexOf("Apple")
clear()Removes all elementslist.clear()
size()Returns number of elementslist.size()
isEmpty()Checks if list is emptylist.isEmpty()

πŸ” Looping Through an ArrayList

🧩 Using for loop

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

🧩 Using for-each loop

for (String fruit : fruits) {
    System.out.println(fruit);
}

🧩 Using forEach() method (Java 8+)

fruits.forEach(System.out::println);

🧠 ArrayList vs Array

FeatureArrayArrayList
SizeFixedDynamic/resizable
Data typesSupports primitivesSupports objects only
Lengtharray.lengthlist.size()
PerformanceSlightly fasterMore flexible
MemoryLess overheadUses extra memory internally

🧰 Real-World Example – Student List

import java.util.ArrayList;

public class StudentApp {
    public static void main(String[] args) {
        ArrayList<String> students = new ArrayList<>();
        students.add("Aman");
        students.add("Sneha");
        students.add("Ravi");

        if (students.contains("Sneha")) {
            System.out.println("Sneha is enrolled.");
        }
    }
}

βœ… Useful in apps like:

  • E-commerce carts
  • To-do lists
  • Dynamic forms
  • Real-time search suggestions

πŸš€ Performance Tips

βœ… Use ArrayList when:

  • You need fast access (get() is O(1))
  • You rarely insert/remove in the middle (those are O(n))

⚠️ If frequent inserts/removals at the beginning/middle are needed, consider using LinkedList.


βœ… Summary

  • ArrayList is a dynamic array structure in Java that supports ordered and duplicate elements
  • Ideal for fast random access and flexible list operations
  • Comes with powerful built-in methods for management and iteration
  • Widely used in real-world Java applications for storing object collections

❓ FAQs – Java ArrayList

❓ Can ArrayList hold primitive types?

No. Use wrapper classes like Integer, Double, etc. (autoboxing handles this automatically).

❓ Is ArrayList synchronized?

No. Use Collections.synchronizedList() or CopyOnWriteArrayList for thread safety.

❓ Can ArrayList store null?

Yes, ArrayList allows null values.

❓ What is the default size of an ArrayList?

Internally, the capacity starts at 10 (but size is 0 until elements are added).

❓ How to convert ArrayList to array?

String[] arr = fruits.toArray(new String[0]);

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java ArrayList

Or Copy Link

CONTENTS
Scroll to Top