Java Article 19 - Intro to Java Collections - Arrays

Arrays are one of the many varieties of collections in Java. A collection is an object that serves as a container for other data. Put another way container objects group multiple values into a single unit (the container object). This single container object can then be manipulated, passed to a method, or acted upon within a loop.

One very cool thing about arrays and the other collections is that they hold objects (technically values that represent the memory locations of the objects). So if you were designing a card game you might put your individual card objects into some kind of collection and then you could do things like copy, search, sort or even randomize the collection of card objects with minimal effort.

It is right about here the terminology in involved with the Collections Framework can get pretty confusing to new programmers. Aside from arrays, the collection classes that you can use as containers are referred to as implementations. There are different categories of implementations, which I am not going to cover here. Different implementations have different interfaces. There are over a dozen interfaces which support the many implementations, and even custom implementations you can create yourself.

Like other classes the collection implementations have methods (algorithms) that can perform various tasks like sorting and searching. The methods a collection class can use depend on the interfaces it implements, just like with other classes you have encountered.

Confused? You should be. Don't worry too much about all the implementation and protocol stuff for now. Just remember there are a lot of different container classes, and each one is useful for storing and manipulating data in a particular way. I will cover some of the more popular implementations in other articles since here we are going to discuss arrays.

While an array is conceptually a collection (an object that holds multiple values), and the Java API states it is part of the Collections Framework, the API also segregates it as one of the old collections that predate the modern new and shiny core collections. It does not implement any of the collection interfaces and it has its own methods. Because of this it is also a bit easier to use, and easier to understand, so it is usually the first collection or container object taught in a Java course.

Another thing that is different about arrays is that they can hold the primitive types (int, double, boolean etc) without special treatment (using a wrapper class).

Arrays are declared like other variables…

int[] myArrayOfInts;

…except for the empty brackets which indicate that this is an array (a single dimensional array).

Since arrays are objects you also have to instantiate them after you declare them:

myArrayOfInts = new int[10];

The "[10]" indicates the length of the array, also referred to as its number of elements. One disadvantage to using arrays is that their length is fixed and cannot be changed. So myArrayOfInts can hold 0 to 10 int values in its 10 elements.

Individual values are added to arrays by specifying the element's index ([0], which has to be an int) and then the value to add to that element:

myArrayOfInts [0] = 12;

Above we add the int 12 to index 0. Index 0 is the first element in an array.

Elements of an array that are not assigned values will have the default empty value for the type: (e.g. numeric types will be 0, Booleans will be false, and objects (including strings) will be "null"; These empty values are inserted when the array is instantiated, then overwritten when you assign values.

As with other objects you can also declare and instantiate your array all in one line. The following diagram summarizes this:

array syntax

Then if we were to add three strings to the array…

myArrayOfNames [0] = "Bob";
myArrayOfNames [1] = "Tom";
myArrayOfNames [2] = "Joe";

...we would have an array object that looked like this:

array diagram

The array is one object as shown by the yellow box, the cups are elements, each element has an index that identifies it, and each element holds a value.

As a bit of a shortcut, you can also declare and instantiate an array as follows:

String [] myArrayOfLetters = {"A","B", "C"};

To retrieve an element from an array we simply use:

System.out.println(myArrayOfLetters [0]);

Or to assign it to an existing variable:

x = myArrayOfLetters [0];

One pitfall when working with arrays is when you try to reference an element that is outside of the bounds of an array:

System.out.println(myArrayOfLetters [3]); // ArrayIndexOutOfBoundsException

This can be a little confusing: while the length is 3, the 3rd index is actually the 4th element, since the index starts counting at 0.

So this program sums up the basics above:

 // this library is only needed for the methods in otherMethods()

import java.util.Arrays;

public class ArrayBasics 
{
	static String [] myArrayOfLetters = {"A","B", "C"};
	
	public static void main(String[] argv)
	{

		//shows the length of the array:
		System.out.println("myArrayOfLetters.length = " 
				+ myArrayOfLetters.length + "\n");
				
		displayArray();//print our array
		modifyArray();//change the 1st element
		displayArray();//print our array again to see the change
		otherMethods();//Other methods of the Array class
	}

	

	private static void displayArray() 
	{
		System.out.println(myArrayOfLetters[0]);
		System.out.println(myArrayOfLetters[1]);
		System.out.println(myArrayOfLetters[2] + "\n");
		
		
		 // Imagine how much typing would you have to do if your 
		 // array had 1000 elements. Therefore you should do
		 // this in a loop. See the next program when you are 
		 // done here.
		 
		 
	}
	
	private static void modifyArray() 
	{
		myArrayOfLetters[0] = "some New Letter";
	}
	
	private static void otherMethods() 
	{
		System.out.println("Here are some other methods " +
				"of the Array class:");
				
		//Add a value to all elements of an array:
		System.out.println("Add a value to all elements " +
				"of an array:");
		Arrays.fill(myArrayOfLetters, "X");
		displayArray();
		
		//Add a value to a range of elements of an array:
		System.out.println("Add a value to a range of " +
				"elements of an array:");
		Arrays.fill(myArrayOfLetters, 0, 2, "Z");
		displayArray();
		
		//Sort the array in ascending order:
		System.out.println("Sort the array in ascending order:");
		Arrays.sort(myArrayOfLetters);
		displayArray();
		
		//Return the index for the specified value in the array:
		System.out.println("X is at index " 
				+ Arrays.binarySearch(myArrayOfLetters, "X"));
		
		//Copy an array to a new array:
		String[] copyOfMyArrayOfLetters 
		= Arrays.copyOf(myArrayOfLetters, myArrayOfLetters.length);
		//There is also copyOfRange to copy just part of an array.
	}
}

The real power of arrays are that they can be used with loops. We can do interesting things with arrays and loops that save us a huge amount of time as can be seen in the following program:

public class ArrayInALoop
{
	static int [] arrayOfInts = new int[10];
		
	public static void main(String[] argv)
	{
		fillArrayOfInts();
		displayArrayOfInts();
		modifyArrayContents();
		displayArrayOfInts();
	}

	
	private static void fillArrayOfInts() 
	{
		
		 // Weather our array has 10 or 10,000 elements this 
		 // will fill it with sequential numbers:
		 
		for (int i=0; i < arrayOfInts.length; i++)
		{
			arrayOfInts[i] = i;
		}
		
	}

	private static void displayArrayOfInts() 
	{
		
		 // Then here we can easily print them all:
		 
		for (int i=0; i < arrayOfInts.length; i++)
		{
			//System.out.println(arrayOfInts[i]);
			System.out.println(arrayOfInts[i]);
		}
		System.out.println("\n");
	}
	
	private static void modifyArrayContents() 
	{
		
		 / Then here we can easily modify the values 
		 // contained within the array:
		 
		for (int i=0; i < arrayOfInts.length; i++)
		{
			//multiply the value in each element by 2:
			arrayOfInts[i] *= 2; 
			
			 // Imagine what a pain it would be doing this to
			 // a very long array without using a loop.
			 
		}
	}
}

You can also have an array of arrays, called a two-dimensional array, or even multidimensional arrays. These follow the same syntax but have additional sets of brackets per dimension:

type[] [] arrayName = new type [X elements] [Y elements];