Overview: What are Arrays and ArrayLists

Arrays and ArrayLists are a set of data elements, all stored under the same name. Arrays can hold all types of data, from integers, characters, decimals and objects such as Strings as well. ArrayLists, unlike arrays, allow us to add elements to it after decleration. are some major differences and advantages of using one over the other, and this lesson aims to educate you about them!

Arrays

An array is a set of data elements that is fixed in size. What this means is that we cannot add any more elements to the array after decleration. Each array can only store one type of data. Arrays are declared like this:

  int powersOfTen = new int[5];


And initialized with values like this:
 powersOfTen = {1, 10, 100, 1000, 100,000}; 
However, because the elements of an array can be from any Java type, these elements can themselves be arrays as well. These are known as 2d or multidimensional arrays. If you wanted to create array space for a 3x3 tic-tac-toe board, this would be the decleration:

  char [] [] board = new char [3][3];
The decleration creates a 2d array of characters which is organized like this:

ArrayList

ArrayList are dynamically sized arrays, meaning the number of elements they have can be changed throughout the code, and elements can be added or removed using methods such as add() or remove().

One of the major differences between arrays and ArrayLists are that ArrayLists are a Java class, rather than a special form. This means that all operations on ArrayLists are done using method calls (we'll be looking at some of the most common methods for ArrayLists below). In addition, we'd use get and set methods to select specific elements, and get the number of elements in the array using the size() method.

In addition, another important thing to remember is that ArrayLists only accept objects, not primitive data types like int or char. Instead, we would use a wrapper class such as the Integer or Double class. We would declare an ArrayList which holds Strings like this:

 ArrayList <String> al = new ArrayList<String> ;


Methods in the ArrayList class

Below are methods used to modify, access and use ArrayLists, courtesy of Stanford's CS106A course.