Arrays in Java Code - dummies

By Barry Burd

The ArrayList class that is used is in many Android app programs is only the tip of the Java collections iceberg. The Java library contains many collections classes, each with its own advantages. The table contains an abbreviated list.

Some Collection Classes
Class Name Characteristic
ArrayList A resizable array.
LinkedList A list of values, each having a field that points to the next
one in the list.
Stack A structure (which grows from bottom to top) that’s optimized
for access to the topmost value. You can easily add a value to the
top or remove it from the top.
Queue A structure (which grows at one end) that’s optimized for
adding values to one end (the rear) and removing values from the
other end (the front).
PriorityQueue A structure, like a queue, that lets certain (higher-priority)
values move toward the front.
HashSet A collection containing no duplicate values.
HashMap A collection of key/value pairs.

Each collection class has its own set of methods (in addition to the methods that it inherits from AbstractCollection, the ancestor of all collection classes).

An array is a particular kind of collection that’s optimized for indexing. That is, you can easily and efficiently find the 100th value stored in an array, the 1,000th value stored in an array, or the 1,000,000th value stored in an array.

The array is a venerable, tried-and-true feature of many programming languages, including newer languages such as Java and older languages such as FORTRAN. In fact, the array’s history goes back so far that most languages (including Java) have special notation for dealing with arrays. The listing illustrates the notation for arrays in a simple Java program.

package com.allmycode.collections;
public class SimpleCollectionsDemo {
  public static void main(String[] args) {
    String[] myArray = new String[4];
    myArray[0] = "Hello";
    myArray[1] = ", ";
    myArray[2] = "readers";
    myArray[3] = "!";
    for(int i = 0; i < 4; i++) {
      System.out.print(myArray[i]);
    }
    System.out.println();
    for (String string : myArray) {
      System.out.print(string);
    }
  }
}

The figure shows the output of a run of the code in the listing. Both the ordinary for loop and the enhanced for loop display the same output.

Running the code in the listing.
Running the code in the listing.

In the listing, the ordinary for loop uses indexes, with each index marked by square brackets. As it is with all Java collections, the initial value’s index is 0, not 1. Notice also the number 4 in the array’s declaration — it indicates that “you can store 4 values in the array.”

The number 4 doesn’t indicate that “you can assign a value to myArray[4].” In fact, if you add a statement such as myArray[4] = “Oops!” to the code in the listing, you get a nasty error message (ArrayIndexOutOfBoundsException) when you run the program.

The statement String[] myArray = new String[4] creates an empty array and makes the myArray variable refer to that empty array. The array can potentially store as many as four values. But, initially, that variable refers to an array that contains no values. It’s not until Java executes the first assignment statement (myArray[0] = “Hello”) that the array contains any values.

You can easily and efficiently find the 100th value stored in an array or the 1,000,000th value stored in an array. Not bad for a day’s work. So, what’s the downside of using an array? The biggest disadvantage of an array is that each array has a fixed limit on the number of values it can hold. When you create the array in the listing, Java reserves space for as many as four String values.

If, later in the program, you decide that you want to store a fifth element in the array, you need some clumsy, inefficient code to make yourself a larger array. You can also overestimate the size you need for an array, as shown in this example:

    String[] myArray = new String[20000000];

When you overestimate, you probably waste a lot of memory space.

Another unpleasant feature of an array is the difficulty you can have in inserting new values. Imagine having a wooden box for each year in your collection of Emperor Constantine Comics. The series dates back to the year 307 A.D., when Constantine became head of the Roman Empire.

You have only 1,700 boxes because you’re missing about six years (mostly from the years 1150 to 1155). The boxes aren’t numbered, but they’re stacked one next to another in a line that’s 200 meters long. (The line is as long as the 55th floor of a skyscraper is tall.)

At a garage sale in Istanbul, you find a rare edition of Emperor Constantine Comics from March 1152. After rejoicing over your first comic from the year 1152, you realize that you have to insert a new box into the pile between the years 1151 and 1153, which involves moving the year 2013 box about ten centimeters to the left, and then moving the 2012 box in place of the 2013 box, and then moving the 2011 box in place of the 2012 box. And so on.

Life for the avid Emperor Constantine Comics collector is about to become tiresome! Inserting a value into the middle of a large array is equally annoying.