Java ArrayList Tutorial with Examples

ArrayList is a resizable array implementation of the List interface in Java. It provides dynamic array capabilities, which means it can grow and shrink as needed. This tutorial will cover all methods of ArrayList with examples and outputs. Additionally, it will highlight key points, use cases, best practices, performance considerations, and a real-time example.

Table of Contents

  1. Introduction
  2. Key Points
  3. ArrayList Methods
    • add()
    • addAll()
    • get()
    • set()
    • remove()
    • clear()
    • size()
    • isEmpty()
    • contains()
    • indexOf()
    • lastIndexOf()
    • toArray()
    • iterator()
    • listIterator()
    • subList()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example
  8. Conclusion

1. Introduction

An ArrayList in Java is a part of the Java Collections Framework and provides a way to manage a dynamic array that can grow and shrink as needed. It is found in the java.util package and is one of the most used data structures in Java.

2. Key Points

  • ArrayList is dynamic in size.
  • It allows duplicate elements.
  • It maintains the insertion order.
  • It is not synchronized.
  • It allows random access of elements.
  • The default capacity of ArrayList is 10.

3. ArrayList Methods

3.1. add()

The add() method is used to insert elements into the ArrayList.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        System.out.println(names);
    }
}

Output:

[Aarav, Vivaan, Diya]

3.2. addAll()

The addAll() method adds all elements of a collection to the ArrayList.

Example:

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.addAll(Arrays.asList("Vivaan", "Diya"));
        System.out.println(names);
    }
}

Output:

[Aarav, Vivaan, Diya]

3.3. get()

The get() method returns the element at the specified index.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        System.out.println(names.get(1)); // Vivaan
    }
}

Output:

Vivaan

3.4. set()

The set() method updates the element at the specified index.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        names.set(1, "Aryan");
        System.out.println(names);
    }
}

Output:

[Aarav, Aryan, Diya]

3.5. remove()

The remove() method removes the element at the specified index or the first occurrence of the specified element.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        names.remove(1);
        System.out.println(names); // [Aarav, Diya]

        names.remove("Diya");
        System.out.println(names); // [Aarav]
    }
}

Output:

[Aarav, Diya]
[Aarav]

3.6. clear()

The clear() method removes all elements from the ArrayList.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        names.clear();
        System.out.println(names);
    }
}

Output:

[]

3.7. size()

The size() method returns the number of elements in the ArrayList.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        System.out.println(names.size()); // 3
    }
}

Output:

3

3.8. isEmpty()

The isEmpty() method checks if the ArrayList is empty.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        System.out.println(names.isEmpty()); // true
        names.add("Aarav");
        System.out.println(names.isEmpty()); // false
    }
}

Output:

true
false

3.9. contains()

The contains() method checks if the ArrayList contains a specified element.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        System.out.println(names.contains("Vivaan")); // true
        System.out.println(names.contains("Diya")); // false
    }
}

Output:

true
false

3.10. indexOf()

The indexOf() method returns the index of the first occurrence of the specified element.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Aarav");
        System.out.println(names.indexOf("Aarav")); // 0
    }
}

Output:

0

3.11. lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of the specified element.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Aarav");
        System.out.println(names.lastIndexOf("Aarav")); // 2
    }
}

Output:

2

3.12. toArray()

The toArray() method converts the ArrayList into an array.

Example:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        String[] namesArray = names.toArray(new String[0]);
        for (String name : namesArray) {
            System.out.println(name);
        }
    }
}

Output:

Aarav
Vivaan
Diya

3.13. iterator()

The iterator() method returns an iterator for the elements in the ArrayList.

Example:

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output:

Aarav
Vivaan
Diya

3.14. listIterator()

The listIterator() method returns a list iterator for the elements in the ArrayList.

Example:

import java.util.ArrayList;
import java.util.ListIterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        ListIterator<String> listIterator = names.listIterator();
        while (listIterator.hasNext

()) {
            System.out.println(listIterator.next());
        }
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}

Output:

Aarav
Vivaan
Diya
Diya
Vivaan
Aarav

3.15. subList()

The subList() method returns a view of the portion of the ArrayList between the specified indices.

Example:

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

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Aarav");
        names.add("Vivaan");
        names.add("Diya");
        names.add("Aryan");
        List<String> subList = names.subList(1, 3);
        System.out.println(subList);
    }
}

Output:

[Vivaan, Diya]

4. Use Cases

  • Dynamic arrays: ArrayList is used when you need a dynamically resizable array.
  • Random access: It allows quick access to elements using the index.
  • Maintain insertion order: ArrayList maintains the order of elements as they are inserted.

5. Best Practices

  • Initial capacity: If the size of the list is known in advance, setting an initial capacity can improve performance.
  • Use generics: Always use generics to ensure type safety.
  • Avoid frequent resizing: Adding elements frequently can cause resizing. Consider setting an appropriate initial capacity.

6. Performance Considerations

  • Resizing: ArrayList grows dynamically, which can cause performance overhead due to array resizing.
  • Memory usage: ArrayList consumes more memory as it maintains an array internally.
  • Thread safety: ArrayList is not synchronized. Use Collections.synchronizedList() if thread safety is needed.

7. Real-time Example

Managing a Student List: Let's create a Student class and manage a list of students using ArrayList.

Student.java:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + "}";
    }
}

Main.java:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("Aarav", 20));
        students.add(new Student("Vivaan", 22));
        students.add(new Student("Diya", 21));

        for (Student student : students) {
            System.out.println(student);
        }
    }
}

Output:

Student{name='Aarav', age=20}
Student{name='Vivaan', age=22}
Student{name='Diya', age=21}

8. Conclusion

The ArrayList class in Java offers a variety of methods for manipulating elements and provides flexibility in managing collections of data. By understanding ArrayList class methods, use cases, and best practices, you can effectively utilize ArrayList in your Java applications.

Related Collections Examples

Comments