java.util package.
package java.util;
public class ArrayList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
// Constructors
// Methods
// Fields
}
RandomAccess marker interface to indicate efficient indexed access.get(index) due to the underlying array structure.
ArrayList Class
ArrayList class:
| Sr. No. | Constructor | Description |
|---|---|---|
| 1 | ArrayList() |
Constructs an empty ArrayList with default initial capacity (10). |
| 2 | ArrayList(int initialCapacity) |
Constructs an empty ArrayList with the specified initial capacity. |
| 3 | ArrayList(Collection<? extends E> c) |
Constructs an ArrayList containing the elements of the specified collection, in the order they are returned by the collection's iterator. |
ArrayList Class
ArrayList class:
| Sr. No. | Method | Description |
|---|---|---|
| 1 | void ensureCapacity(int minCapacity) |
Increases the capacity of the ArrayList, if necessary, to ensure it can hold at least the number of elements specified. |
| 2 | void trimToSize() |
Trims the capacity of this ArrayList instance to be equal to its current size, reducing memory usage. |
ArrayList inherits all the methods of List and Collection interface.
ArrayList class.
import java.util.ArrayList;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<>();
// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Mango");
list.add("Banana"); // duplicate allowed
System.out.println(list);
System.out.println("-------------------------");
// Accessing element
System.out.println("Element at index 2: " + list.get(2));
System.out.println("-------------------------");
// Updating element
list.set(1, "Orange");
System.out.println(list);
System.out.println("-------------------------");
// Removing element
list.remove("Apple");
System.out.println(list);
System.out.println("-------------------------");
// Iterating ArrayList
for(String fruit : list)
{
System.out.println(fruit);
}
}
}
[Apple, Banana, Mango, Banana] ------------------------- Element at index 2: Mango ------------------------- [Apple, Orange, Mango, Banana] ------------------------- [Orange, Mango, Banana] ------------------------- Orange Mango Banana
ArrayList Class:
index 0.Collections.sort() or list.sort().
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.