Prev Next

Arrays

What if you wanted to work with several instances of a class? For example, consider the scenario when you want to sort several Point instances along x-axis (from left to right). It would be tedious to declare a new variable for each instance of Point class.

Working with Array of Objects

An array is a container object that holds a reference to certain number of objects of a single type. And you can refer to them using index where the index ranges from 0 to length of the array. The length of an array is fixed when an array is created.

We will now create an array of Points in the test driver.

    Point[] points = new Point[5];

This creates a single array object that contains reference to 5 Point instances.

Each of the 5 Point instances has to be created explicitly.

  points[0] = new Point(2,5); // 1st element
  points[2] = new Point();    // 3rd element (set to (0,0) by default constructor)
  points[3] = new Point(-4,4);   // 4th element 

The methods of these instances can be invoked. For example

  System.out.println( points[0].slope(points[2]) );     // prints 2.5
  System.out.println( points[2].distance(points[3]) );  // prints 8

Try the following and check what happens?

  • System.out.println( points[1] ); // points[1] not created yet

  • points[3].add( points[4] ).print(); // points[4] not created yet

  • points[7].print(); // index 7 is greater than the length

  • System.out.println( points.length ); // length is an attribute of array object

You can use a loop to create all instances in one go. For example, following code creates a set of 20 Point instances in a 10x10 grid with arbitrary x and y values. Thereafter it computes the slope from point[0] to every other point.

  Point[] points = new Points[20];

  for (int i = 0; i < 20; i++)
    points[i] = new Point(i*31%11,i*59%11); // i*31(mod 11), i*59(mod 11)

  for (int i = 1; i < 20; i++)
    System.out.println( "The slope of " + points[0] 
                        + " and " + points[i] 
                        + " = " + points[0].slope( points[i]) );

Exercise: Add a loop to the above driver code to determine the number of duplicate points and print the duplicates. Since we have assigned the coordinates arbitrarily, it is possible that there are duplicates.

Another way to shrink the two-step process of creating an array into one is as follows:

  Point[] points = {  new Point(1,-1), new Point(-2,5), new Point(-7,0),
                      new Point(), new Point(0,8), new Point(-3,-11)
                  }

The length of the array is set to 6 by default.

A sort method for Point class

Add a static method sort() to the Point class to sort the points from left to right. It should take a Point array as argument, sort them based on x-coordinate and return the sorted array.

Why static? Because sort is not specific to a particular instance of Point. In fact, it works on a group of points.

  /** We will use the Selection sort logic. */

  public static Point[] sort(Point[] points) {
      int n = length - 1;             // last index is length - 1
      for (int i = 0; i < n; i++) {   // loop from index 0 to n-1
        int k = minimumX(i, n);       // minimum index from i to n
        points[i].swap(points[k]);    // Swap
      }
  }

  public static int minimumX(int start, int end) {
      minIndex = start;
      for (int j = start+1; j <= end; j++) {
        if (points[j].getX() < points[minIndex].getX())
          minIndex = j;
      }
      return minIndex;
  }

    public void swap(Point q) {
      Point temp = new Point();
      temp.x = this.x;
      temp.y = this.y;

      this.x = q.x;
      this.y = q.y;

      q.x = temp.x;
      q.y = temp.y;
    }
  }

Note that minimumX() and swap() are useful methods that can potentially be used on occasions other than sorting. Hence, we declared them as public. minimumX() works with array of points from the start to end indices. Hence, it is declared static. On the other hand swap() involves just 2 points and hence is an instance method.

Implement test drivers to check the working.

  Point[] points = new Points[20];

  for (int i = 0; i < 10; i++)              // populate the points
    points[i] = new Point(i*31%11,i*59%11); 

  Point.sort(points);                       // sort the points

  for(int i = 0; i < 10; i++)               // print the sorted points
    System.out.println( points[i] );

Exercise: To get comfortable working with arrays, you can implement the following methods.

  1. Improve the logic of minimumX() such that if x-coordinates are same, the one with the least y-coordinate should be considered smaller.
  2. And if both x and y happen to be same, you can pick anyone arbitrarily.
  3. maximumX()
  4. minimumY()
  5. maximumY()
  6. reverse() - reverse the array.
  7. The above is a mutable implementation of sort. Implement a non-mutable version by creating a new sorted array and returning it instead of changing the existing array.
  8. Implement a different sorting algorithm, say insertion sort.

Arrays of primitive data types

For working with arrays of primitive data types creation of array object is enough. You don't have to create individual instances explicitly. For example,

  int[] intArray = new int[5];
  intArray[0] = 100;    // Start working with the elements
  intArray[1] = 200;    // of the array immediately
        :
        :

Primitive data types: byte, short, int, long, float, double, boolean, char.

Direct initialization of primitive data types is also possible.

  float[] floatArray = {2.8, 3.5, 15.6, 7.99}; // floatArray.length is set to 4 automatically
  char[] charArray = {'a', 'b', 'c'};  // charArray.length is set 3