Java ArrayList
Java ArrayList
ArrayList in Java is a part of the java.util package. It is a resizable array, which means elements
can be added or removed dynamically.
1. Creating an ArrayList
To create an ArrayList, you need to import java.util.ArrayList and then instantiate it.
Example:
import java.util.ArrayList;
2. Inserting Values
Example:
import java.util.ArrayList;
3. Deleting Values
You can remove values using the remove method by index or by value.
Example:
import java.util.ArrayList;
4. Reversing an ArrayList
Example:
import java.util.ArrayList;
import java.util.Collections;
5. Sorting an ArrayList
Example:
import java.util.ArrayList;
import java.util.Collections;
9. The ArrayList class does not have a built-in method named merge. However, you can merge
two ArrayLists manually by using the addAll() method or iterating over one list and adding its
elements to another.
Using addAll()
The addAll() method adds all the elements from one list to another.
Example:
import java.util.ArrayList;
list1.add(1);
list1.add(2);
list1.add(3);
list2.add(4);
list2.add(5);
list2.add(6);
list1.addAll(list2);
ADDITIONAL
ArrayList Methods
1. Adding Elements
2. Accessing Elements
list.add(10);
3. Updating Elements
● set(int index, E element): Replaces the element at the specified index with the
specified element.
4. Removing Elements
5. Searching Elements
indexOf(Object o): Returns the index of the first occurrence of the element, or -1 if not
found.
lastIndexOf(Object o): Returns the index of the last occurrence of the element.
trimToSize(): Reduces the storage capacity of the ArrayList to its current size.
● forEach(Consumer<? super E> action): Performs the specified action for each
element.
● subList(int fromIndex, int toIndex): Returns a view of the portion of the list between
the specified indices.
9. Comparing Lists
● equals(Object o): Compares the list with another object for equality.
toArray(T[] a): Converts the list into the specified type of array.