Alternate Array Syntax
• The brackets of the array type can be associated with the element type or with the
name of the array
• Therefore the following two declarations are equivalent:
float[] prices;
float prices[];
• The first format generally is more readable and should be used
7-1
Initializer Lists
• An initializer list can be used to instantiate and fill an array in one
step
• The values are delimited by braces and separated by commas
• Examples:
int[] units = {147, 323, 89, 933, 540,
269, 97, 114, 298, 476};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
7-2
Initializer Lists
• Note that when an initializer list is used:
– the new operator is not used
– no size value is specified
• The size of the array is determined by the number of items in the initializer list
• An initializer list can be used only in the array declaration
7-3
Primes
int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
System.out.println ("Array length: " + primeNums.length);
System.out.println ("The first few prime numbers are:");
for (int index = 0; index < primeNums.length; index++)
System.out.print (primeNums[index] + " ");
7-4
Arrays as Parameters
• An entire array can be passed as a parameter to a method
• Like any other object, the reference to the array is passed, making the formal and
actual parameters aliases of each other
• Therefore, changing an array element within the method changes the original
• An individual array element can be passed to a method as well, in which case the
type of the formal parameter is the same as the element type
7-5
Arrays as Parameters
public static void doubleValues(int[] x) {
for (int i = 0; i < x.length; i++) {
x[i] *= 2;
}
}
int[] x = {1, 3, 5};
doubleValues(x); //method call
for(int val:x)
System.out.print(val + " ");
7-6
Two-Dimensional Arrays
• A one-dimensional array stores a list of elements
• A two-dimensional array can be thought of as a table of elements,
with rows and columns
one two
dimension dimensions
7-7
Two-Dimensional Arrays
• To be precise, in Java a two-dimensional array is an array of
arrays
• A two-dimensional array is declared by specifying the size of
each dimension separately:
Int rows = 5, cols = 10;
int[][] scores = new int[rows][cols];
• A array element is referenced using two index values:
value = scores[3][6]
• The array stored in one row can be specified using one index
7-8
Two-Dimensional Arrays
Expression Type Description
table[5][12] int[][] 2D array of integers, or
array of integer arrays
table[5] int[] array of integers
table int integer
7-9
Two Dimensional Array
public static void main (String[] args) {
int[][] table = new int[5][10];
// Load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = row * 10 + col;
// Print the table
for (int row=0; row < table.length; row++) {
for (int col=0; col < table[row].length; col++)
System.out.print (table[row][col] + "\
t");
System.out.println();
}
} 7-10
Output
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
7-11
Multidimensional Arrays
• An array can have many dimensions – if it has more
than one dimension, it is called a multidimensional array
• Each dimension subdivides the previous one into the
specified number of elements
• Each dimension has its own length constant
• Because each dimension is an array of array references,
the arrays within one dimension can be of different
lengths
– these are sometimes called ragged arrays
7-12
Ragged Arrays
• Ragged arrays have rows of unequal length
– each row has a different number of columns, or entries
• Ragged arrays are allowed in Java
• Example: create a 2-D int array named b with 5 elements in the first row, 7 in the
second row, and 4 in the third row:
int[][] b = new int[3][];
b[0] = new int[5];
b[1] = new int[7];
b[2] = new int[4];
Searching an Array
• There are many techniques for searching an array for a particular
value
• Sequential search:
– start at the beginning of the array and proceed in sequence until
either the value is found or the end of the array is reached*
• if the array is only partially filled, the search stops when the
last meaningful value has been checked
– it is not the most efficient way
– but it works and is easy to program
* Or, just as easy, start at the end and work backwards toward the
beginning
Example: Sequential Search of an Array
// return location of item if found; assume unique elements
// return -1 if item not found
public int searchArray (int[] array, int item)
{
int location = -1;
for (int i = 0; i < array.length; i++) // check all elements
if (array[i] == item)
location = i;
return location;
}
Using Arrays
• The iterator version of the for loop can be used when processing
array elements
for (int score : scores)
System.out.println (score);
• This is only appropriate when processing all array
elements from top (lowest index) to bottom
(highest index)
• See BasicArray.java (page 372)
7.6 Enhanced for Statement
• Enhanced for statement
– New feature of J2SE 5.0
– Allows iterates through elements of an array or a collection
without using a counter
• This is only appropriate when processing all array elements from
top (lowest index) to bottom (highest index)
7.6 Enhanced for Statement - Syntax
• Enhanced for statement
– Syntax
for (dataType elementVariable : array) {
statements
}
• Where dataType – The type of the array
• elementVariable – A variable that holds the value of
the current iteration’s element (user defined).
• array – The array in which we are iterating through.
1 // Fig. 7.12: EnhancedForTest.java
2 // Using enhanced for statement to total integers in an array.
3
4 public class EnhancedForTest
5 {
6 public static void main( String args[] )
7 {
8 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
9 int total = 0;
10 For each iteration, assign the next
11 // add each element's value to total element of array to int
12 for ( int number : array ) variable number, then add it to
13 total += number;
total
14
15 System.out.printf( "Total of array elements: %d\n", total );
16 } // end main
17 } // end class EnhancedForTest
Total of array elements: 849
7.6 Enhanced for Statement (Cont.)
• Lines 12-13 are equivalent to
for ( int counter = 0; counter < array.length; counter++ )
total += array[ counter ];
• Usage
– Can access array elements
– Cannot modify array elements
– Cannot access the counter indicating the index
Array Implementations Overview
• Relatively fast insertions
• Iterating over the records simple
• Records are sorted by their insertion time
• If order needs to be preserved, removal is a difficult process,
otherwise deletions are fast, too.
• Finding an item needs sequential search, therefore not very efficient