If you have any query feel free to chat us!
Happy Coding! Happy Learning!
ArrayList
is a dynamic array-like data structure provided by Java's standard library in the java.util
package. It is part of the Java Collections Framework and implements the List
interface, which means it maintains an ordered collection of elements with duplicates allowed. Unlike regular arrays, ArrayList
automatically resizes itself to accommodate new elements when the current capacity is reached, making it more flexible and convenient to use.
To use ArrayList
, you need to import the java.util.ArrayList
class. Here's how you can create and work with an ArrayList
:
Creating an ArrayList: To create an ArrayList
, you can use the default constructor, which creates an empty list with an initial capacity of 10, or you can use the constructor that takes an initial capacity as an argument.
javaCopy code
import java.util.ArrayList;
// Create an empty ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
// Create an ArrayList with an initial capacity of 20
ArrayList<String> names = new ArrayList<>(20);
Adding Elements: You can add elements to an ArrayList
using the add()
method.
javaCopy code
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
Accessing Elements: You can access elements in an ArrayList
using the get()
method, providing the index of the element you want to retrieve.
javaCopy code
String firstFruit = fruits.get(0); // "Apple"
String thirdFruit = fruits.get(2); // "Orange"
Removing Elements: You can remove elements from an ArrayList
using the remove()
method, providing either the index of the element you want to remove or the element itself.
javaCopy code
fruits.remove(1); // Removes the element at index 1 (Banana)
fruits.remove("Apple"); // Removes the element "Apple"
Size and Checking Empty: You can get the number of elements in the ArrayList
using the size()
method and check if it is empty using the isEmpty()
method.
javaCopy code
int size = fruits.size(); // Size of the ArrayList
boolean isEmpty = fruits.isEmpty(); // Check if the ArrayList is empty
Iterating Over ArrayList: You can use the enhanced for loop (for-each loop) or the traditional for loop to iterate over the elements in an ArrayList
.
javaCopy code
for (String fruit : fruits) {
System.out.println(fruit);
}
ArrayList
provides various other methods like contains()
, indexOf()
, clear()
, etc., for different list operations.javaCopy code
if (fruits.contains("Apple")) {
int index = fruits.indexOf("Apple"); // Get the index of "Apple"
}
fruits.clear(); // Remove all elements from the ArrayList
ArrayList
is a very commonly used data structure in Java due to its flexibility and easy-to-use methods for managing collections of data.
Comments: 0