Mark As Completed Discussion

ArrayList

The ArrayList class in Java is a resizable array implementation of the List interface. It provides various methods that allow you to add, remove, and access elements in the ArrayList.

To use the ArrayList class, you need to import the java.util.ArrayList package.

Here's an example that demonstrates the usage of the ArrayList class:

TEXT/X-JAVA
1import java.util.ArrayList;
2
3public class Main {
4
5  public static void main(String[] args) {
6    // Create an ArrayList
7    ArrayList<String> arrayList = new ArrayList<>();
8
9    // Add elements to the ArrayList
10    arrayList.add("Element 1");
11    arrayList.add("Element 2");
12    arrayList.add("Element 3");
13
14    // Access elements in the ArrayList
15    String element = arrayList.get(1);
16    System.out.println("Element at index 1: " + element);
17
18    // Update an element
19    arrayList.set(0, "Updated Element");
20
21    // Remove an element
22    arrayList.remove(2);
23
24    // Check if an element exists
25    boolean exists = arrayList.contains("Element 2");
26    System.out.println("Element 2 exists: " + exists);
27
28    // Get the size of the ArrayList
29    int size = arrayList.size();
30    System.out.println("Size of the ArrayList: " + size);
31  }
32
33}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment