CSIT115 Class 9

Note discussion page for hw2 on Wiki

Class exercise: Automobile.java

We’ll continue with this example next time.

  

Hw2—about arrays mainly, arrays of ints, then arrays of objects. Arrays are objects, so we access them through references, and there can be multiple references to the same array, which is good and bad—

·         Good because we can pass them to a method and change them in the method and these changes “stick” after return from the method

·         Bad because it can be confusing if you have two names for the same array and changes are made though one name and show up under the other name.

 

By request, looked at #1, about list1,list2, … on pg. 462.  Here the names list2 and list3 are aliases for the same array object, as shown in the diagram.

When the assignment list2[2] = 0 is executed, the lower array object is changed to {1,3,0,7,9}, but the upper array object remains as before.

Thus list1[2] = 5, list2[2] = 0, and list3[2] = 0 after this assignment.

 

By request, looked at #2, prob. 15, pg. 492, which illustrates the difference between ints and objects when passed to a method.

 

Here x=1, a = {0,0,0,0) at the point of the first call to mystery.

Inside that call, x starts off at 1, a copy of the value of x at the call.

Inside that call, x = 2, so a[2] is incremented to 1, and a = {0,0,1,0} after that.

After the return, back in main, x=1, because the change done inside mystery was on a copy of this x, not on x itself.

After the return, however, a = {0,0,1,0}, because the whole array object was passed to the method (by copying its reference), and any changes to it survive the return.

 

By request, looked at #7

We need to create an array of two Points named pair. This means an array whose elements are Point objects.

Point[] pair = new Point[2];

Compare this to creating an array of 2 ints:

int [] pair1 = new int[2];

Here int and Point are Java types.

 

Example of method that modifies an array: incrementAll, pg. 422

 

public static void incrementAll(int[] data) {

  for (int i=0; i < data.length; i++) {

    data[i]++;

  }

}

 

In main:

  int a[] = {1,2,6};

  int b[] = a;

  incrementAll(a)

 

<picture of a and b refs pointing to one array of ints, before and after>

 

  What is a[1] now?    a[1] was 2, was incremented to 3

  What is b[1] now?  also 3, because it’s the same array object.

 

 

Another thing to notice: we can return a whole array from a method.

Example in book: pg. 442 buildOddArray.