Lecture23-24: More Arrays

  1. Do the normal set up: log on, open this page, open JCreator, create a lecture folder, and be prepared to take notes and solve problems.
  2. Either download and unzip this file or download the files from this folder.
  3. Midterm Exam 2 is being handed back. Answers are available on the web site. Out of 50 points, the high score was 42, the median score 38, and the low score 25.
  4. Programming Exam 1 is due TUESDAY at 3:00pm. There is NO regrade opportunity!
  5. Midterm evaluation results are available here.

Array Summary (so far)

Arrays are used to hold collections of objects of the same type. We use [] when we declare an array:

    private Line[] spoke;

When we construct an array, we specify its size:

    spoke = new Line[9];

We can access an array element by indexing into it, remembering that array indices start at 0.

    spoke[0] = new Line(0, 0, 40, 150, canvas);

You can obtain the physical length of an array with a public variable.

   int physicalLength = spoke.length;

Often the array will only be partially filled. In such cases, it is important to maintain another variable that has the logical length of the array.

    int numberInSpoke = 1;

A for loop is very useful for walking through arrays and repeating operations on each element:

    for (int i = 0; i < numberInSpoke; i++)
    {
        spoke[i].setColor(Color.RED);
    }

Array indices should stay between 0 and one less than the declared size. If they don't, you will get an ArrayOutOfBoundsException. Also, array elements must be initialized before you can use them. If they aren't, you will probably get a NullPointerException.

Demonstrations

For Reference Afterward