Arrays

Normal Arrays

Up until now variables have held one value. What if you need to store a known number of values in a certain order? You would use an array. An array is just a list of objects or variables. An array of integers could be defined like this int[] myArray; It would then have to be filled with values. In the following example two different ways are shown to store values in an array.

Alphabet.java

public class Alphabet
{
    public static void main(String args[])
    {
	//store the whole alphabet in array ourAlphabet
	char[] ourAlphabet = {'a','b','c','d','e','f','g','h'
			,'i','j','k','l','m','n','o','p','q'
			,'r','s','t','u','v','w','x','y','z'};

	//Display the first item stored in ourAlphabet.. Notice the zero
	System.out.println("First element: " + ourAlphabet[0]);
	//Display the last item stored in ourAlphabet.. Notice the 25
	System.out.println("Last element: " + ourAlphabet[25]);

	//create a new array called codeAlphabet of length 26
	char[] codeAlphabet;
		codeAlphabet=new char[26];

	//fill it with an alphabet that has been shifted left one character
	for(int i = 0; i<codeAlphabet.length;i++)
	{
		
		/*set codeAlphabet to (each letter + 1)
		when the end of the alphabet is reached
		start at the beginning again*/
		codeAlphabet[i]=ourAlphabet[(i+1)%ourAlphabet.length];
	}

	//Display the first item stored in codeAlphabet	
	System.out.println("Encoded a: "+codeAlphabet[0]+"\n"
			+"Encoded z: "+codeAlphabet[25]);
    }
}

Input

javac Alphabet.java
java Alphabet

Output

First element: a
Last element: z
Encoded a: b
Encoded z: a

Two arrays were defined; both storing characters; both of length 26. It's important to remember that the first element of an array is ZERO not ONE. If you wanted the character in slot 1 to be a and slot 26 to be z you would need to make an array of size 27 and leave the 0th element empty.

Also note how we access an element... if we want to use element 5 of an array called myArray, we need to type myArray[4]. We could set a variable to this value: x = myArray[4]; or we could set the 5th element to the value of x like so: myArray[4] = x;

Mod (%) is used in a tricky way in the above program. If we didn't use mod the codeAlphabet would be trying to add something from slot 26 into its' own slot 25. ourAlphabet doesn't have a slot 26 because our slot counts start at zero, slot 25 is element 26 (slot zero is element 1). The mod just divides (i+1) by the length of the alphabet and checks for a remainder. The remainder will be (i+1) unless (i+1) is the same length or longer than the alphabet's length. In which case the count starts at zero because the remainder of a number divided by itself is zero. This makes zero based arrays quite convenient.

ArrayLists

What if you didn't know how long the array would be? You would need something that could resize itself. ArrayLists are that something.

NumberList.java

//we need this line to use ArrayLists
import java.util.ArrayList;
public class NumberList
{
    public static void main(String args[])
    {
	//Notice the use of Integer instead of int
	ArrayList<Integer> anArray = new ArrayList<Integer>();

	anArray.add(1);//put 1 in the empty list
	anArray.add(2);//put 2 in the second slot (slot 1)

	//display the ArrayList size
	System.out.println("The size of the array is: "+anArray.size());

	//display the ArrayList
	System.out.println(getString(anArray));
	
	//change the first element to 5 (slot 0 will contain 5)
	anArray.set(0,5);

	//display the ArrayList
	System.out.println(getString(anArray));
	
	//remove the first element (slot 0) and display it
	System.out.print(anArray.remove(0)+" has been removed ");
	
	//display the element that is now in slot zero
	System.out.println(anArray.get(0)+" is now in it's place");

	//display current array size
	System.out.println("The size of the array is: "+anArray.size());

	//display the array
	System.out.println(getString(anArray));
    }

    //this method returns a displayable String for an Integer ArrayList
    public static String getString(ArrayList<Integer> inList)
    {
	String temp = "{ ";

	//This loop sets i to the next value of inList every round.
	for(Integer i : inList)
	    {
		//add the element and a space to temp
		temp += i + " ";
	    }

	temp += "}";
	return temp;	
    }
}

One thing you might notice is that we use the word Integer instead of int. That's because int is a primitive data type. Only non-primitive data types can be used in this area because they need to be objects. Integer is the object version of int known as a wrapper class it's basically an int with some methods attached to it. Wrapper classes are quite useful and they will be discussed in detail in the next lesson.

2D arrays

A 2d array is an array of arrays. Here are some examples:

4 x 5 integers5 x 5 integers5 x 5 characters 5 x 5 characters (ragged)3 x 6 integers (ragged)
 01234
015815
126215
237115
348615
 01234
000000
101234
202468
3036912
40481216
 01234
0gcjfo
1hbddn
2kxsjq
3zrahw
4ysgte
 01234
0a-jk4
1f+ h2
2(  ,}
3d  /$
4'  + 
 012345
070-1   
1555555
2496132

In the above examples we see what are known as matrices in mathematics. An array of an array is in fact a matrix. int[][] aMatrix; defines a matrix called aMatrix. It can then be instantiated (as a 3 x 2 matrix) like this: aMatrix = new int[3][2]; and initialized like this:

aMatrix[0][0]=0;
aMatrix[0][1]=0;
aMatrix[1][0]=0;
aMatrix[1][1]=0;
aMatrix[2][0]=0;
aMatrix[2][1]=0;

or all three steps can be done in one, like this:int[][] aMatrix={{0,0},{0,0},{0,0}};

A non-ragged array is just an array with length n x m (height times width of the 2d array). A ragged array is an array of arrays where the arrays contained within the primary array are not required to be of the same length. A ragged array is usually an array of resizeable arrays. The size of the array containing the arrays must be known when initializing a 2d-array using a normal array but the sizes of the secondary arrays can be left out. If you use an ArrayList for both the primary and secondary arrays, the lengths can be modified at runtime.

Arrays can be made to any dimension but they are difficult to define and understand geometrically past 3-dimensions.

BlueVoxel.java

import java.awt.Color;
public class BlueVoxel
{
    public static void main(String args[])
    {
	//create a 1 x 1 x 1 array of colors and store blue in it
	Color[][][] World3d = {{{new Color(0,0,255)}}};
	
	//if voxel at (0,0,0) is blue display: "the world is blue"
	if(World3d[0][0][0].equals(Color.blue))
	    {
		System.out.println("the world is blue");
	    }
	else
	    {
		System.out.println("the world is not blue");
	    }
    }
}

new Color(0,0,255); is blue as our program shows. How does it work? Well it mixes different levels of red green and blue from 0 to 255 to make any color you can see on the screen. Like this: new Color(RED,GREEN,BLUE); so to make red would be new Color(255,0,0); and white would be new Color(255,255,255); you could also just use Color.blue;

A voxel is defined as a volumetric pixel, or a pixel placed in a data structure that gives it 3d coordinates. A pixel is a pi(x)cture element; a colored dot that can be part of a picture. All the tiny colored dots on your computer screen are called pixels. If your computer screen had 3 dimensions instead of 2 it would have voxels.

Another important thing that you should remember is that we use .equals (pronounced dot equals) instead of = = . Why is that? One reason is because java does not allow operator overloading. Operator overloading is when you add methods to a class that allow instances of your class to be compared with symbolic operators like = = and >. Since java doesn't have this feature you can know that all class based variables use .equals and all primitive data types use = = and all the other comparators covered in the logic section. The wrapper classes in the next section should use .equals.