Subscribe to Dogstopper's Code Mania        RSS Feed
-----

Java Arrays Galore!

Icon Leave Comment
Hello again, thanks for reading!

There are many continuing questions on the forums recently that really deserve explanation. Arrays. Most of the time, these questions could be answered just by looking at a simple guide to arrays. That's what this is for!

Single Dimensional Arrays
Single dimensional arrays can be thought of as a series of variables in sequence. They can be accessed by an index, which specifies what ELEMENT of the array you want to access. Sounds simple? Actually, they are! In a minute, I will show you how an array works, but first, you must understand important concepts of an array:
  • Array lengths always measure how long (number of elements) the array is/has, so if you have an array that has 13 elements, the array's length will be 13.
  • Elements of the arrays are 0 based, which means that the firast element is 0 and the last is length-1. (In the case of 13 element long array, the last element is at index number 12).
But what does this all mean? That means that instead of this:
int num1 = 1;
int num2 = 2;
int num3 = 3;
...
int num100 = 100;



We can simply define an array that is 100 digits long and then use a loop (usually a for loop) to set each index's number.
// Define an array of length 100
int[] array = new int[100];

// Cycle through each element and set each to its own index plus 1.
// (Remember, arrays a 0-based.)
for (int i = 0; i < array.length; i++) {
	array[i] = i+1; // Set the element at index i to i+1.
}

// Now we have an array of 100 elements that have the number 1-100. Just to
// Show you something unique, test yourself, what will the following line output?
System.out.println(49);



See how much better that was? It also allows for you to have very easily adjustable code if ever you need more or less elements. By the way, the answer to the question posed above is 50, because we set each element to contain a number 1 greater than their index. If you understand most of this thus-far, you are in good shape!

.length attribute
Well, often arrays are changed as the programmer moves along, and very often, runtime exceptions can be avoided simply by not using hard coded numbers in arrays; most often, it is better to use an attribute that changes its size as soon as the array does. Let me show you:

This is an example of bad code:
int[] array = new int[10];

// ... Fill array with numbers

// Print all ten elements
for (int i = 1; i <= 10; i++) {
	System.out.println(i);
}



That code is incorrect because the user forgot that arrays are 0-indexed and not only never printed the first element, but it actually tried the access the non-existent 11th element. Because of this, the Java Virtual Machine throws an ArrayIndexOutOfBounds exception. This exception indicates that error.
Instead, using the .length attribute can prevent many such errors like this.

int[] array = new int[10];

// ... Fill array with numbers

// Print all ten elements remembering it is 0 based
for (int i = 0; i < array.length; i++) {
	System.out.println(i);
}



Remember, the last index will ALWAYS be one smaller than its length so you want to use the < operator not the <=

Multidimensional arrays
Not satisfied with a single dimension? Usually, there is a better way to approach a situation, but often, such as when imitating a board game or doing matrix math, you will want an array that has rows and columns. These are known as 2-dimensional arrays. I'm not going to go into this TOO much, but I can start you off with a simple example.

// Create a multidimensional array
int[][] array = new int[20][20];

// Fill array
for (int i = 0; i < array.length; i++) { // Cycle through the rows
	for (int j = 0; j < array[i].length; j++) { // For each row, cycle through the columns
		array[i][j] = i+j;
	}
}

// access an element like so: 
int element = array[10][11];
System.out.println(element);



Remember to use the array.length on the outer row, and remember to use array[i].length on the columns, because columns can actually be different lengths from each other (ragged arrays). I generally don't ever RECOMMEND ragged arrays, but they exist, so them I teach.
int array[][] = new int[10][];

// Now make 10 columns of increasing length.
for (int i = 0; i < array.length; i++) {
	array[i] = new int[i+1]; // Make an array off of the row.
}


Again, I don't generally recommend this, but if you must, you must.

A final note: multidimensional arrays aren't limited to 2 dimensions...but beware of memory loss...

The foreach loop
The foreach loop has been recently introduced into Java 5. It is extraordinarily useful for immediately accessing elements of an array without having to mess with an index.

int[] array = new int[20];

// I'm going to skip filling the array up. Just remember that you must.

// Print each element directly.
for (int x : array) {
	System.out.println(x);
}



Well, that's actually really simple so I'll just leave you with a word of caution. When using this loop be careful of concurrency issues (multithreading), especially when using this access method to remove an element while the foreach is running....

Anyway, I hope that this sums up arrays!

Thanks for reading
-- Stephen Schwahn

0 Comments On This Entry

 

December 2018

S M T W T F S
      1
2345678
91011121314 15
16171819202122
23242526272829
3031     

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)