ArrayList Methods
Introduction to ArrayList Methods
- Understand that ArrayList is a resizable array in Java, located in the java.util package.
- Recognise that unlike arrays, ArrayLists can grow and shrink automatically.
ArrayList Declaration and Initialization
- Declare an ArrayList with
ArrayList<data-Type> listName = new ArrayList<>();
. - Initialise an ArrayList with values using
Arrays.asList()
, such asArrayList<Integer> numbers=new ArrayList<Integer>(Arrays.asList(1,2,3,4));
.
Adding Elements
- Use the
add(element)
method to append elements at the end of the ArrayList. - Use the
add(index, element)
method to insert an element at a specific index.
Accessing Elements
- Use
get(index)
method to retrieve an element at a specific index.
Removing Elements
- Implement
remove(index)
method to delete an element at a specified index. - Use
remove(Object)
to remove a specific object/element from the ArrayList.
Updating Elements
- Use
set(index, element)
method to update an element at a specific index.
Checking if ArrayList is Empty
- Apply
isEmpty()
that returns true if ArrayList is empty, false otherwise.
Size of ArrayList
- Implement
size()
method to find the number of elements in an ArrayList.
Searching in ArrayList
- Use the
contains(object)
method that returns true if the element is found, false otherwise. - Implement
indexOf(Object)
method to get the index of the first occurrence of an element in the ArrayList.
Converting ArrayList to Array
- Use
toArray()
method to convert an ArrayList into an array.
Clearing ArrayList
- Implement
clear()
method to remove all elements from the ArrayList.
Remember to import java.util.ArrayList and possibly java.util.Arrays before using ArrayLists in your programs.