ArrayLists

Dynamic data structures in Java

One of the limitations of Arrays is that they have a set length once they have been initialized. Because of this, Java has another data structure called ArrayList.


ArrayLists are objects that store elements similar to how arrays store elements. The major difference is that elements are able to be added at any position of the ArrayList and removed from any position. Here is the implementation and uses of some of the methods in the ArrayList class.

ArrayList declaration and initialization (for an int ArrayList):

ArrayList<Integer> myList = new ArrayList<Integer>();

or if you would like to give a set length beforehand, use

ArrayList<Integer> myList = new ArrayList<Integer>(length);


IMPORTANT:

Because object parameters cannot take in primitive types such as int, make sure to use the object boxing of the primitive type such as Integer, Double, Character, Float, etc.

In order to add elements to the end of the ArrayList, use

myList.add(E);

where E is the element you would like to add to the end of the list.

If you would like to add the element at a specific index, use

myList.add(pos, E);

where pos is the position that the element will take after it has been added into the ArrayList.

In order to remove elements from the ArrayList, use

myList.remove(pos);

Where pos is the position of the element to remove. This method will return the removed item as a value.

If at any time you would like to access the size/length of the arraylist, simply call

myList.size();

and it will return an integer with the size of the ArrayList.

The Enhanced For-Loop or For-Each Loop

The enhanced-for loop or for-each loop can be used if you would like to access each and every element in an array or ArrayList. The syntax is as follows:

int sampleArray[] = {1, 2, 3};

for (int element : sampleArray) {

System.out.print(element + " ");

}

This is equivalent to doing

int sampleArray[] = {1, 2, 3};

for (int i = 0; i < sampleArray.length; i++) {

System.out.print(sampleArray[i] + " ");

}

Using an enhanced for-loop would be the same for an ArrayList.

It is important to note that when using an enhanced for-loop, you can not modify the elements in the actual array or ArrayList. The element used to access elements is a copy of the original item. If you do modify elements of the list, add elements, or remove elements from the ArrayList, this will throw a ConcurrentModificationException.