In Java, ArrayList
is a part of the java.util
package and provides a resizable array implementation backed by an array. It dynamically grows and shrinks as elements are added or removed. Here's a basic overview of how to use ArrayList
:
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { // Create an ArrayList ArrayListlist = new ArrayList<>(); // Add elements to the ArrayList list.add("Apple"); list.add("Banana"); list.add("Orange"); // Access elements in the ArrayList System.out.println("Elements in the ArrayList:"); for (String fruit : list) { System.out.println(fruit); } // Get the size of the ArrayList int size = list.size(); System.out.println("Size of the ArrayList: " + size); // Remove an element from the ArrayList list.remove("Banana"); // Check if an element exists in the ArrayList boolean containsOrange = list.contains("Orange"); System.out.println("ArrayList contains Orange: " + containsOrange); // Clear all elements from the ArrayList list.clear(); // Check if the ArrayList is empty boolean isEmpty = list.isEmpty(); System.out.println("ArrayList is empty: " + isEmpty); } }
This example demonstrates creating an ArrayList
, adding elements to it, accessing elements, getting the size, removing elements, checking if an element exists, clearing the ArrayList
, and checking if it's empty. ArrayList
provides many more methods for manipulation and retrieval of elements.