| What is an array? | An array is a list of items. A variable that has been declared as int can hold just one value at a time, but a variable that has been declared as an array can hold many at the same time. |
| How are arrays declared? |
Putting square brackets next to a variable type says that you want to use a variable that is an array of that type, such as int[] or double[]. When you use new you can specify how large the array is.
double[] highTemperatures = new double[7]; // give me an array that can hold the daily high temperature char[] ch = new char[131]; // define an array that can hold a line of text input from a keyboard int [] daysInMonths = new int[12]; // maybe 13 if you want to index this by month number
The variable is defined to have an integer array type, but no space has been allocated for it. Like other class objects, the memory space for the array is not allocated until the new command is given. long[] powersOfTwo = new long[20];
is the same as having the two statements:
|
| How to read a list of numbers into an array |
// read in a list of batting averages (doubles) as command line arguments
public class battingAverage {
public static void main (String[] args) {
int argc = args.length; // this tells us how many command line arguments there are
double[] ba = new double [args.length]; // allocate space for each command line argument
for (int i = 0; i< argc; i++) {
ba[i] = Double.parseDouble(args[i]); // does the coversion from String to double
// write out the batting averages just to trace the program
System.out.printf("found batting average: %d %1.3f \n", i, ba[i]);
}
}
}
|
| How to print the contents of an array? |
// this code will print out the batting average array, it goes from 0 to (ba.length - 1). // to print them in the revese order they were read in, start with (ba.length -1) and go down to 0.
for (int i = 0; i< ba.length; i++) {
System.out.printf("Batting average: [%d] = %1.3f \n", i, ba[i]);
// notice this uses printf and I want the batting averages to always
// show 3 decimal places
}
|
| How to sort an array? |
There are many ways to sort arrays, here is one take on a "bubble sort"
// sort the array - from low to high
// First find the lowest value, put it in ba[0],
// fint the next lowest value, put it in ba[1]..and so on
// Efficiency is not a consideration here
for (int i = 0; i < (ba.length - 1); i++) {
for (int j = i+1; j < ba.length; j++) {
if (ba[i] > ba[j]) { // switch the two
double temp = ba[i]; // save it
ba[i] = ba[j]; // move lower number toward start
ba[j] = temp; // move higher numbers toward end
}
} // j loop
} // i loop
|
| Can I define an array of objects or just the basic data types? | Yes, just keep in mind that decalaring array doesn't allocate space, the new command does. |