JDEP183H

Handout 29:  Harnessing the Power of Arrays

 

October 24, 2006

 

Arrays of Objects vs. Arrays Numerical Data Types

 

The following is valid:

 

double[] rainfall;

rainfall = new double[12];

rainfall[0] = 13.0;

rainfall[1] = 12.5;

 

However, the following is not valid (assuming that we are given the Orc class as defined in our homework assignments):

 

Orc[] myOrcs;

myOrcs = new Orc[10];

myOrcs[0].setName(“Ali Baba”);

 

The above will give you a null pointer exception.  Why?  What is the difference between the Orc example and the double example?

 

The difference is that double is a numerical data type, and Orc is an object or reference data type.  When dealing with an array of a reference data type, in addition to creating the space to hold the array, we need to create the individual memory space for each object of the reference data type as well.  As a result, the following is necessary:

 

Orc[] myOrcs;

myOrcs = new Orc[10];    // this only creates an array

myOrcs[0] = new Orc();   // we need to create the Orc object!

myOrcs[0].setName(“Ali Baba”);


 

Modifying Arrays with Method Invocations

 

Consider the following methods:

 

            public static int[] obtainInt() {

        int[] number;

        number = new int[2];

   number[0] = 1;

   number[1] = 2;

   return number;

      }

 

            public static void processInt(int[] number) {

   number[0] = number[0]+number[1];

   number[1] = number[0]*number[1];

   }

      }

 

And then consider this:

 

1    int[] num = obtainInt();

2    processInt(num);

3    System.out.println(num[0]);

4    System.out.println(num[1]);

 

What is the output of lines 3 and 4?  What does line 1 do?  Note that obtainInt() returns an array!  As a result, we do not have to create additional space for the array num in line 1.  Suppose we split line 1 into the following:

 

     int[] num = new int[2];

     num = obtainInt();

 

What does that do?  It means that we create an array of two integers for the array num.  Immediately after that, we call obtainInt() which also creates an array of two integers and returns that array.  As a result, the spaces initially created for the array num are now in a limbo state – no longer pointed to by the array num!  (Sooner or later, the garbage collector will sweep them up.)

 

Now, furthermore, what does line 3 do?  In the method processInt(), the array is modified.  After the method terminates, will the modifications stay with the array? YES!!!  When an array is passed into a method, it is passed in as a reference data type.  As a result, changes made to the array will remain as such even outside of the method.

 

* Based on Wu (2004).