Page 1 of 1

Introduction: Arrays A beginner's introduction to the array structure Rate Topic: ***** 3 Votes

#1 Mila  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 33
  • View blog
  • Posts: 193
  • Joined: 28-October 06

Posted 08 May 2007 - 08:15 PM

1: What is an Array?
An array is a special java data structure that allows us to group together groups of like variables in an easy-to-manage grouping. The most similar real-world concept is a table. When an array is declared and instantiated, the compiler sets apart a given number of memory addresses in order for the array itself.

An array is a fixed-length structure. This means that if you declare an array of length 10, the compiler will set apart exactly ten memory locations in a row. No more, no less. Your array will have exactly 10 indices, and cannot be grown to length 11 or shrunk to length 9.

All arrays contain a single type of data. You can have an int array or a Random array (of random number generator objects from a library such as java.util.Random), but you cannot have an array of both, say, ints and chars.

When you create and instantiate an array, the compiler, as we said before, sets apart a given number of memory locations for storage. The default value of each of these locations, however, is determined by the data type of the array. For any objects, the default value is null; for ints, 0; doubles, 0.0; booleans, null (false); etc.

Seeding an array or giving each location value must be done manually, usually through the use of for-loops or a special constructor.

Arrays are hard-coded into the virtual machine and do not require the importing of any libraries.

2: One-Dimensional Arrays
A one-dimensional array is the most basic array. If considered as a table, a one-dimensional array would be a vertical table with one column and a certain number of rows. This is, in fact, the simplest way of considering this type of data structure.

The syntax for declaring an array is as follows:
type[] variableName;

// for example, an array of ints
int[] intArray;

// for example, an array of Random objects
Random[] randomArray;

// alternative, less-used declarations:
int intArray[];
int[] intArray[];


There are two different ways of instantiating an array. The first simply creates an object of the Array class of a certain length, assigning each location a default value:
// first type of instantiation: creating an object of a certain length
type[] variableName = new type[size];

// for example, an array of 5 ints
int[] intArray = new int[5];

// for example, an array of 5 Random objects
int size = 5;
Random[] randomArray = new Random[size];


The concept of default values was covered back in 1. If we were to print out each member of intArray as instantiated above, we would have: 0 0 0 0 0. Likewise, each location of randomArray has a null value as no Random object has physically been assigned to each location.

The second actually assigns values directly, and is less common. This method only works if you declare and instantiate in the same declaration:
// for example, an array of 5 ints
int[] intArray = {1,2,3,4,5};


2.1: Index and Length
Accessing each location of an array is done through the use of indices. Each row in the table that represents an array is indicated via its index, a number starting at 0 and ranging up to, but not including, the size you instantiated the array for. An array of length 10, instantiated as int[] intArray = new int[10], has indices 0 - 9.

The syntax for accessing the information within a specific location in the array is as follows:
variableName[n]
where variableName is an array whose length is greater than n, and where n is an int, byte, short, or char within the proper range.

All indices are of type int, byte, short, or char because all of these primitives can be promoted to type int. Attempting to use doubles, Integers, objects, longs, or anything else will result in a compilation error.

If you attempt to access an index which is out of the range of an array, your program will throw an ArrayIndexOutOfBoundsException and, unless precautions are taken, crash.

In order to assign values to each position within the array, it is necessary to use the indices to access each position in order and assign values. The most common method is using a for-loop.
int size = 5;
int[] intArray = new int[size];

for (int index = 0; index < size; index ++)
{  intArray[index] = index;  }


The for-loop displayed above traverses the array and assigns each position the value of its index. If the intArray array were printed, this would be the output: 0 1 2 3 4.

Notice that the for-loop ran as long as the index was less than but not equal to the size of the array. intArray is of length 5, and includes the indices 0 - 4; intArray[5] is out of the bounds of the array. Had the for-loop header read:
for(int index = 0; index <= size; index ++)
then the program would have thrown an ArrayIndexOutOfBoundsException when the for-loop reached the point of assigning a value to intArray[5].

Any array will easily tell you its length (that is, its maximum index + 1). This is done via the following syntax:
variableName.length
This returns an int representing the length of the array. Note that there are no parentheses following the word length because it is not a method.

So, for int[] intArray = new int[5], a call to intArray.length would return 5.

This makes the for-loops used for instantiation very simple to code:
int[] intArray = new int[x]; //x is some int declared & instantiated previously

for (int index = 0; index < intArray.length; index ++)
{  intArray[index] = 2*index + 1; }


2.2: Changing the Size of the Array
An array, as we mentioned before, is fixed-length. So if you have an array of length 10, it will have 10 locations, no matter if you fill them or not. But be aware that if your array has any "blank" locations, these will be filled with the default value, and count towards the total length.

Thus, an array instantiated and filled like this:
int[] intArray = new int[5];
for (int index = 0; index < 3; index ++)
{  intArray[index] = index + 1;  }

would display this, if printed: 1 2 3 0 0.

The only way to make your array "grow" or "shrink" is to physically copy each item from your existing array into a new array and then resave the new array to the previous variable name. Complicated as that sounds, the algorithm used is quite simple:
1. create a temporary array of your desired size
2. using a for loop, access each item from the original array and save it to the corresponding index of the temporary array
3. save the temporary array into the variable for your original array.

Here's an example:
int[] intArray = new int[5];
for (int index = 0; index < 3; index ++)
{  intArray[index] = index + 1;  }

int[] tempArray = new int[3];
for (int index = 0; index < tempArray.length; index++)
{  tempArray[index] = intArray[index];  }

intArray = tempArray;

Notice how the second for-loop runs while index < tempArray.length. The reason for this is simple: if it were to run until index < intArray.length, not only would it thrown an ArrayIndexOutOfBoundsException, but you would also be saving values you didn't want into your new shrunken array.

The algorithm might become slightly trickier if you wanted to, say, save all odd indices between 3 and 55 into a new array. The base rule, however, is that each item must be accessed individually and saved into a new array.

Also, intArray = tempArray is executed, both variable names are pointing to the same memory location. The series of memory locations that had previously been the array intArray has disappeared forever into the jaws of the java trash collector. This also means that if you later modify an index of tempArray, a call to that index of intArray will reflect your modifications.

3: Two-Dimensional Arrays
A two-dimensional array is, technically, an array of arrays. That is, if in a one-dimensional array each member represented a row, in a two-dimensional array each of those row-members now contains its own one-dimensional array ... the columns.

It is sometimes easier to instead think of a two-dimensional array as a physical table with rows and columns, each labeled with an index of 0 to its maximum bound.

Declaration and instantiation of 2D arrays is quite similar to that of 1D arrays:
int rows = 3, cols = 4;
int[][] tableArray = new int[rows][cols];

for (int rowIndex = 0; rowIndex < rows; rowIndex ++)
{
	for (int colIndex = 0; colIndex < cols; colIndex ++)
	 {   tableArray[rowIndex][colIndex] = rowIndex * colIndex + 1; }
}

The logic behind the code is this: for each row, fill each column with this value. The outer for-loop controls the rows and the inner for-loop controls the columns.

The alternative constructor is also available for the 2D array, though slightly more confusing:
int[][] tableArray = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};

//or, alternatively (and more easily understood since it looks more like a table:
int[][] tableArray = { {1, 2, 3, 4, 5}
								{6, 7, 8, 9, 0} };


3.1: Length
There is actually a third way to initialize a 2D array. You can initialize a 2D array without initializing the columns, but you must initialize the rows:
int[][] tableArray = new int[5][]; // this is ok
int[][] tableArray = new int[][5]; //this is NOT ok


Why is this?

In a 2D array, the length of the columns may vary. This comes from the array-of-arrays way of considering a 2D array rather than as a table. The following is a perfectly valid printout of a 2D array:
012
0123
01234

Thus, since only the number of rows is a given, a call to variableName.length, where variableName is a valid 2D array, would return the number of rows (or, technically, the length of the 1D array which contains arrays).

In order to determine the length of each row (ie: the number of columns in a row), you need to pick a row and then call length.

So for int[][] tableArray = new int[5][], a call to tableArray.length will return 5 (the number of rows). If we wanted to know how many columns there were in the first row, we would call tableArray[0].length.

The same rules apply for 2D arrays in regards to changing size and assigning variables (as mentioned in 2.2).

4: Etc
You are not limited to 1- and 2-dimensional arrays. 3-dimensional arrays are sometimes used in higher-level programming, and the even higher dimensional arrays, though increasingly rare and difficult to maintain, are possible.

The most obvious limitations of this storage structure is that an array can only hold one type of element. Almost equally obvious is the fact that you need to know the exact number of elements that will be kept in the array at the time you're making the array, and this number has to stay constant. Though it is possible, with the use of temporary arrays, to "shrink" and "expand" arrays, these methods are inefficient and waste resources.

Arrays are useful, but do not have pre-designed methods for sorting, inserting, deleting, and searching; that is, if you want to do any of these things, you have to rely on your own abilities to write the appropriate code to do this. If you are looking for a data structure to do any of these functions, it is possible (but extremely inefficient) to use arrays, but it may make more sense to seek out a different data storage structure.

Is This A Good Question/Topic? 1
  • +

Replies To: Introduction: Arrays

#2 chachejave  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 24-February 08

Posted 20 April 2008 - 05:50 PM

:^: This is a great overview of arrays. Great to read after trying to create an array for the first time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1