The ArrayList
class in Java is a resizable array that implements the List
interface. It provides methods for adding, removing, and accessing elements in the list, as well as methods for searching, sorting, and iterating over the elements of the list.
Here is an example of how to create an ArrayList
and add elements to it:
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> words = new ArrayList<>(); words.add("hello"); words.add("world"); words.add("goodbye"); words.add("moon"); } }
This code creates an ArrayList
of strings called words
and adds the elements "hello", "world", "goodbye", and "moon" to the list using the add()
method.
You can also create an ArrayList
from an existing collection using the ArrayList(Collection<? extends E> c)
constructor. For example:
import java.util.List; import java.util.Arrays; ... List<String> list = Arrays.asList("hello", "world", "goodbye", "moon"); ArrayList<String> words = new ArrayList<>(list);
This code creates a List
of strings using the asList()
method of the Arrays
class and assigns it to the list
variable. It then creates an ArrayList
of strings called words
and initializes it with the elements of the list
List
.
To access the elements of an ArrayList
, you can use the get()
method, which takes an index as an argument and returns the element at that index. For example:
String first = words.get(0); String second = words.get(1);
This code gets the elements at index 0
and 1
in the words
list and assigns them to the first
and second
variables, respectively.
You can also use the set()
method to replace an element in the list .