Introduction to ArrayList
Introduction to ArrayList
Basics of ArrayList
- An ArrayList offers a dynamic data structure, where the size can change as needed, unlike regular arrays in Java.
- Arraylists belong to the
java.util
package and therefore, this package needs to be imported for using ArrayLists. - An ArrayList can store elements of a specific type, similar to arrays. However, it allows for greater flexibility in terms of manipulation of data.
- In ArrayLists, the indices start at 0, as with arrays.
Declaration and Initialisation of an ArrayList
- ArrayList in Java is declared:
ArrayList<DataType> listName = new ArrayList<>();
. DataType
can be any Object data type likeInteger
,String
,Double
etc.- Instances of ArrayLists are initialised by calling the constructor with
new ArrayList<>()
. - Preliminary values can be added during initialisation using
Arrays.asList()
:ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4));
.
Manipulating Elements in an ArrayList
- The
add(element)
function is used for appending elements at the end of the ArrayList. - For insertion of elements at specific indices,
add(index, element)
is used. - To access elements,
get(index)
is employed. - The
remove(index)
function allows for deletion of elements from a given index. - The entire ArrayList can be emptied by calling
clear()
.
Additional Methods for ArrayList Handling
- The
size()
function returns the total number of elements present. isEmpty()
is used to check if an ArrayList is devoid of elements, returning true if so, and false otherwise.- To search for an element’s presence,
contains(object)
is used, where a true value indicates the object is in the list. - The
toArray()
function allows for conversion of the ArrayList to an array.
Remember to always import java.util.ArrayList and possibly java.util.Arrays when manipulating ArrayLists in Java programs.