ArrayList

Definition

ArrayList is a class that is part of Java's API (java.util). It is basically an Array that can be expanded or shrunk at will without creating a new Array.

Benefits

It is advantageous to use an ArrayList, rather than an Array, for two main reasons.
- (As mentioned above), you can expand or shrink an ArrayList at will without having to make a new one.
- If you were to add or delete a spot in the ArrayList the shifting of the other variables would be done automatically.

Code

Creating an ArrayList is quite simple, and very similar to creating an Array.

The following would give you an ArrayList of strings:

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

Then to fill in the array, a simple "for-loop" can be written to fill in the ArrayList with whatever elements are needed.

Methods

Some methods available form the Java API for ArrayList are as follows:

Add

Adds a specific element at the given index in the ArrayList, shifting all the greater indicies over one.

arrList.add(int index, E element);

or

Adds a specific element at the end of the ArrayList.

arrList.add(E element);

Remove

Removes a specific element from a desired place in the ArrayList.

Remove can be done in three different ways:

1. Remove the element at a specified index.

arrList.remove(int index);

2. Removes a single instance of a specified element if it is present in the ArrayList.
arrList.remove(Object o);

3. Removes all elements from a specified fromIndex, inclusive, to a specified toIndex, exclusive.
arrList.removeRange(int fromIndex, int toIndex);

Size

Returns number of elements in ArrayList.

arrList.size();

Clear

Clears ArrayList of all elements.

arrList.clear();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License