The ArrayList
class is a part of the Java Collections Framework and is a resizable array that implements the List
interface. The List
interface is a member of the java.util
package and extends the Collection
interface.
The ArrayList
class provides methods to manipulate the elements of a list, such as adding, removing, and accessing elements by index. It also provides methods to search, sort, and iterate over the elements of the list.
Here is an example of how to create an ArrayList
and add some 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"); } }Source:www.lautturi.com
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 access the elements of the ArrayList
using the index of the element in square brackets:
String secondWord = words.get(1);
This code gets the element at index 1
in the words
list and assigns it to the secondWord
variable.
You can use the size()
method to get the number of elements in the ArrayList
:
int size = words.size();
This code gets the size of the words
list and assigns it to the size
variable.
You can use the contains()
method to check if an element is present in the ArrayList
:
boolean containsMoon = words.contains("moon");
This code checks if the words
list contains the element "moon" and assigns the result to the containsMoon
variable.
The ArrayList
class also provides methods to remove elements from the list, such as the remove()
and clear()
methods. You can use the sort()
method to sort the elements of the list according to their natural ordering, or you can use a comparator to specify a custom sorting order.