ArrayList Operations
ArrayLists provide a wide range of operations that can be performed to manipulate and work with the elements stored in the list. Here are some common ArrayList operations:
Adding Elements
To add elements to an ArrayList, you can use the add()
method. This method appends the specified element to the end of the list. For example:
1ArrayList<String> names = new ArrayList<>();
2names.add("Alice");
3names.add("Bob");
4names.add("Charlie");
Accessing Elements
You can access the elements of an ArrayList by their index using the get()
method. The index starts from 0 for the first element and goes up to size() - 1
for the last element. For example:
1String firstElement = names.get(0);
2String secondElement = names.get(1);
Modifying Elements
If you want to modify an element at a specific index in the ArrayList, you can use the set()
method. This method replaces the element at the specified index with the new element provided. For example:
1names.set(2, "David");
Removing Elements
To remove an element from the ArrayList, you can use the remove()
method. This method removes the element at the specified index from the list. For example:
1names.remove(1);
Other Operations
Aside from the mentioned operations, ArrayLists also provide other useful methods such as:
size()
: Returns the number of elements in the ArrayList.isEmpty()
: Checks whether the ArrayList is empty or not.contains()
: Checks whether the ArrayList contains a specific element.
ArrayLists offer flexibility and convenience in performing various operations on the elements stored in the list. These operations allow you to manipulate and work with the data in different ways based on your specific requirements and use cases.
xxxxxxxxxx
}
// ArrayList Operations
import java.util.ArrayList;
public class ArrayListOperations {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> names = new ArrayList<>();
// Add elements to the ArrayList
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Get the size of the ArrayList
int size = names.size();
System.out.println("Size of the ArrayList: " + size);
// Access elements by index
String firstElement = names.get(0);
String secondElement = names.get(1);
System.out.println("First element: " + firstElement);
System.out.println("Second element: " + secondElement);
// Modify elements
names.set(2, "David");
System.out.println("Modified ArrayList: " + names);
// Remove elements