2. Arraylist class
The java.util.ArrayList class provides resizable array and implements the List interface.
Some important points about ArrayList:
It is grownable.
It implements all optional list operations & it also permits all elements includes null.
It provides method to manipulate the size of the array that is used internally to store the
list.
The constant factor is low compared to that for the Linked List implementation.
JAVAArrayList the difference between a built-in array and an ArrayList in Java, is that
the size of an array cannot be modified.
If you want to add or remove elements to/from an array, you have to create a new one.
While elements can be added and removed from an ArrayList whenever you want.
3. Methods in Arraylist
Add( ) inserts the element to the arraylist
addAll( ) adds all elements of a collection to arraylist
clear( ) removes all the elements from arraylist
removeAll( ) removes multiple elements from the arraylist
Remove( ) removes the single element from the arraylist
size( ) returns the length of an arraylist
contains( ) checks if the element is present in the arraylist
containsAll( ) checks if a collection is a subset of arraylist
retainAll( ) retains only the common elements
4. Example
The ArrayList class has many useful methods.
In this example, I use the add() method to add elements to the ArrayList.
import java.util.ArrayList;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> cars =new ArrayList<String>();
cars.add("Volve");
cars.add(“BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars):
}
}
5. Examples of Arraylist Methods
To access an element in the ArrayList, use the get() method refer to the index number:
cars.get(0);
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
To modify an element, use the set() method and refer to the index number:
cars.set(0, "Opel");
To remove an element, use the remove() method and refer to the index number:
cars.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
cars.clear();
To find out how many elements an ArrayList have, use the size method:
cars.size();