Chapter 12
Arrays
Using Arrays
Arrays hold lists of primitive data or objects. So far, if you’ve wanted to store, say, a list of ten Strings, you’ve needed ten separate variables (e.g., nameOne, nameTwo, nameThree, etc.). An array allows you to store all of those Strings under a single identifier (e.g. names) This makes it much easier to work with groups of things.
When declaring an array, you must specify the type of data it will hold and the number of elements (size). Here’s how you’d declare and instantiate an array called nums that holds 8 integers:
int[] nums = new int[8];
(If you’re wondering, that String[] that you incorporate in each main method signature is actually an array of Strings. While we don’t do it in this course, when running a Java application, you can pass String parameters into the main method)
You can also initialize an array by providing initial values in { } (called an initialization list), like so:
//the length of this array would be automatically set to 4
String[] names = {"Alice", "Bob", "Carly", "David"};
Elements are accessed via their index (position in the array) by writing arrayName[index]. In this case, we refer to the index as a subscript. Like Strings, arrays are zero-indexed, meaning the first element is at index 0, not 1. In the example above, names[1] contains “Bob” and names[3] contains “David.” Writing names[5] would generate an “index out of bounds” exception, because there is no index 5 in the array.
Note that is it is typical to say, “names sub one” for names[1].
To set or change the value of an element in an array, access it the same way, as in names[2]=”Nick”;
- In Java, the length of an array cannot be changed once it’s created.
- Length is a (public) property of the array, not a method, so to find the length of the array above, we would write names.length, not names.length().
- The index of the last element in an array is always the length of the array minus one (e.g. names.length - 1), because an array with 4 elements, for example, has indices (plural of index) 0 through 3.
Multi-dimensional Arrays
You can also create multi-dimensional arrays in Java. These are essentially “arrays of arrays.”
Look at the example below, that might hold low and high temps for each day over a 3-day period.
double[][] temperatures = {{38.0, 97.1}, {41.3, 88.4}, {38.2, 85.2}};
To access the high temperature on the third day (i.e., the second element in the third array, you would write temperatures [2][1] (which would 85.2 in this case). Note that the arrays within the arrays do not have to be the same length, but often they are. You can also create arrays of more than two dimensions.
Traversing an array
A for loop is typically used to traverse (go through) an array, usually to write values into the array or read values from the array. The example below would store 100 even numbers (2, 4, 6, …, 200) in an array called evens. Note how the variable i starts at 0 and will go to 99 (one less than the array’s length).
int[] evens = new int[100];
for (int i=0; i< evens.length; i++){
evens[i] = 2*(i+1);
}
Let’s analyze the code above:
When i=0, 2*(i+1) = 2*(1) = 2
When i=1, 2*(i+1) = 2*(2) = 4
When i=2, 2*(i+1) = 2*(3) = 6
…
When i=99, 2*(i+1) = 2*(100) = 200.
The enhanced for loop
An enhanced for loop (also called a for-each loop) is another way to traverse (go through) an array. The syntax is:
for(type variable : array)
In the previous example, you could replace
for (int i=0; i< evens.length; i++)
with
for (int i : evens)
and it would work the same. The name "for each" comes from thinking, "for each int in evens..."
ArrayList Class
There is a library class in Java called ArrayList that has several useful features, including:
- ArrayLists can be resized. Adding an element to an ArrayList automatically increases its size by one (and deleting an element decreases its size).
- New values can be inserted into any position in an ArrayList and any pre-existing elements will “move up” to make way for the new element.
ArrayLists can only contain objects-- not primitive types (although you can use wrapper classes if you need to convert a primitive type into an object).
Because ArrayList is a class, ArrayList instances are objects. To create a new ArrayList, write
ArrayList a = new ArrayList(), where a is its name (identifier).
Some important methods for ArrayLists are:
- add (Object obj) inserts an element at the end
- add(int index, Object obj) inserts an element at index
- set (int index, Object obj) replaces existing element
- get (int index) gets the element at index
- remove (int index) removes the element at index
- size () gets the number of element*
Note that size() is a method in the ArrayList class, as compared to the length property of an array.
ArrayList is one of many classes in the Collections framework, which provide interfaces and classes for other types of collections, as well, including Set (where repeated elements only count once), Hashtable (which stores key:value pairs), and more.)