COMP1000 Week 9

Arrays in a Nutshell

  • To declare an array, use square brackets [] after the data type (e.g., int[]).
  • A variable containing a reference to an array is created.
  • Memory allocation for the array is done using new (e.g., new int[10]).
  • Loops, especially for loops, are commonly used to iterate through array elements.
  • Array elements are accessed using square brackets with an integer index (e.g., array[index]).
  • Array indices start at 0 and end at one less than the array's length.

Example Program

  • The program declares two integer arrays, circleX and circleY, each with a size of 10.
  • The mousePressed function adds the mouse coordinates to the arrays when the mouse is clicked, up to a maximum of 10 clicks.
  • A for loop draws circles at the stored mouse click locations with an index number next to each circle.
  • Advice to students include:
    • Updating attributes in classes.
    • Updating global values in the main tab.
    • Separating concerns like animation display and event handling.

Shifting Array Elements

  • To make space for a new point when the array is full, existing elements can be shifted either to the left or right.
  • When shifting elements, out-of-bounds errors can occur if the loop iterates beyond the array's boundaries.
  • Functions/methods should be used once to encode and can then be reused.

Finding the Maximum Value in an Array

  • An algorithm is presented to find the maximum xx and yy values in the arrays and draw a rectangle.
  • The algorithm iterates through the used elements, comparing each element to the current maximum.

Passing Arrays to Functions

  • A function maxArray is created to find the maximum value in an integer array.
  • The function takes an integer array as a parameter and returns the maximum value.
  • Another function is created to insert a an element into an array.

Values vs. References

  • Arrays is passed to the function by reference, not by value. Changes made to the array inside the function will affect the original array.
  • Primitive types (int, boolean, float, etc.) are passed by value, while arrays and objects are passed by reference.

Objects as Parameters

  • Objects, like arrays, are passed by reference.
  • A detect method is added to the Disk class to detect collisions with another disk.
  • The detect method takes another Disk object as a parameter and checks if the distance between the two disks is smaller than the diameter and if the one disk isn't protected.
  • Push method is used to push the object away.