The Coder's Handbook

ArrayLists

WHAT IS AN ARRAYLIST?

An ArrayList is a lot like an array. It is a data structure and it starts counting at zero. You can access individual elements by index. It is different because it has a few very useful features:


  • It contains handy elements to add, remove, clear elements

  • It is dynamically sized, meaning it can change size after it has been created


As you progress in this course, the ArrayList will become your default data structure.

USING ARRAYLISTS

Declaring and Initialization


To make an ArrayList, you’ll need to both declare and initialize it:


ArrayList<String> words;

words = new ArrayList<String>();


This is often put into a single line:


ArrayList<String> words = new ArrayList<String>();


Notice that there is no initial size. An ArrayList starts out empty.



Iteration


Let’s consider a common example of using an Array-List: looping through the list and printing each element.



for(int i = 0; i < words.size(); i++)

{

System.out.println(words.get(i));

}


Notice that compared to a normal array, it uses the .size() method and .get() method.

ADDITIONAL METHODS

Want to know everything that an ArrayList can do? Check out the official reference.

Size and Contents

  • size() Returns the number of elements in the list

  • isEmpty() Returns true if the list is empty, false otherwise

  • get(int index) Returns the element at index

  • contains(Object o) Returns true if the list contains an instance of the specified object

  • indexOf(Object o) Returns the index position of the first instance of the object (-1 otherwise)


Adding

  • add(Object o) Adds an object to the end of the list

  • add(int index, Object o) Inserts an object to the list at the specified index, pushing the rest back

  • set(int index, Object o) Sets the element at the specified index equal to the given object


Removing

  • clear() Removes all elements from the list

  • remove(int index) Removes the element at index

  • remove(Object o) Removes the first instance of o from the list, if it is present

RESOURCES