ArrayList in Java
ArrayList in Java is a resizable array implementation of the List interface provided by the Java Collections Framework. It allows us to store and manipulate a collection of elements dynamically, which means that we can add, remove, or modify elements at runtime.
To use ArrayList in Java, you first need to import the java.util.ArrayList package, and then create an instance of the ArrayList class. Here's an example:
javaimport java.util.ArrayList;
public class Example {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<Integer>();
// Add some elements to the ArrayList
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Print the ArrayList
System.out.println(numbers);
// Access elements of the ArrayList using an index
int firstNumber = numbers.get(0);
System.out.println("The first number is: " + firstNumber);
// Remove an element from the ArrayList
numbers.remove(2);
// Print the ArrayList again
System.out.println(numbers);
}
}
In this example, we create an ArrayList of integers, add some elements to it, print the ArrayList, access an element using an index, remove an element, and print the ArrayList again.
ArrayList has many useful methods such as add, remove, get, set, size, and clear, which allow us to manipulate the collection of elements. It also has an iterator which allows us to iterate through the elements of the ArrayList.
Comments
Post a Comment