JMU
Understanding the Use of Arrays
with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review: Opinions?

What do you think of the following fragment?

    total = 0.0;
    
    total = total + income1;
    total = total + income2;
    total = total + income3;
    total = total + income4;
    total = total + income5;
    total = total + income6;
    total = total + income7;

    mean = total / 7.0;
    
Review: An Example of an Array

Arrays offer the same kinds of benefits of subscripts in mathematical notation -- this fragment is more compact, more readable, and more flexible.

    total = 0.0;
    for (int i=0; i<n; i++)
    {    
        total = total + income[i];
    }

    mean = total / income.length;
    
Review: An Array in Memory
images/array.gif
Review: A Physical Analogue
Review: Arrays in Java
Elements of Arrays as Parameters
Arrays as Parameters
Returning an Array
Attributes and Methods Owned by Arrays
An Example of the length Attribute
    int       i;
    int[]     strikeouts;

    strikeouts = new int[9];

    for (i=0; i<strikeouts.length; i++) 
    {
        strikeouts[i] = 0;
    }
    
An Example of the length Attribute (cont.)
    int       i;
    int[]     strikeouts;

    strikeouts = new int[9];

    .
    .
    .

    // This will not work because the length attribute 
    // is declared to be final (which means it cannot be
    // changed after it is initialized)
    //
    strikeouts.length = 5;

    
An Example of the clone() Method
    int[]     copy, original;

    original    = new int[3];
    original[0] = 2001;
    original[1] = 1995;
    original[2] = 2001;

    copy = original.clone();
    
Common Faults and Symptoms
Arrays Utility Class

The Arrays class (in the java.util package) class contains several static methods that are very convenient when working with arrays.

    import java.util.Arrays;

    int     target;
    int[]   a;

    a = new int[100];

    Arrays.fill(a, 0);        // Fill a with zeroes
    Arrays.fill(a, 1, 10, 99) // Fill a[10] thru a[99] with ones

    ...

    Arrays.sort(a);           // Sort a in ascending order


    //  Searches for 5 in a and returns 5 if found
    //  The array must be sorted
    //
    target = Arrays.binarySearch(a,5);