Arrays

Declaring & Initializing Arrays

An array is a named sequence of contiguous variables of the same type.

The following declarations declare two length 0 arrays:

double[] scores;
Point[] locations;

Assume the following declaration:

int CAP = 10;

We can initialize these to length 10 arrays as follows:

scores = new double[CAP];
locations = new Point[CAP];

Of course the declaration and initialization can be a single line:

double[] scores = new double[CAP];
Point[] locations = new Point[CAP];

Each variable in an array can be accessed using subscript notation. For example, here is how we can increment each score:

for(int index = 0; index < scores.length; index++) {
   scores[index] = scores[index] + 1;
}

Note that scores.length = 10.

Note that the index ranges from 0 to 9. This can be a source of errors. For example:

scores[10] = scores[10] + 1; // ERROR!

Will cause an "index out of range" error.

Note: At this point locations[index] == null for each index, while scores[index] = 1.0.

If the elements are known in advance, a small array can be initialized as follows:

int[] primes = {2, 3, 5, 7, 11};

We can also create anonymous arrays to be passed as inputs to methods:

computeAverage(new double[] {43.5, 62.7, 83.1});

Example: Vector Arithmetic

class VectorUtils {

   public static double[] add(double[] vec1, double[] vec2) {
      if (vec1.length != vec2.length) {
         System.err.println("Vectors must have same dimension");
         System.exit(1);
      }
      int dim = vec1.length;
      double[] result = new double[dim];
      for(int i = 0; i < dim; i++) {
         result[i] = vec1[i] + vec2[i];
      }
      return result;
   }

   public static void display(double[] vec) {
      System.out.print("<");
      for(int i = 0; i < vec.length; i++) {
         System.out.print(" " + vec[i]);
      }
      System.out.println(" >");
   }


   public static double dot(double[] vec1, double[] vec2) {
      if (vec1.length != vec2.length) {
         System.err.println("Vectors must have same dimension");
         System.exit(1);
      }
      int dim = vec1.length;
      double result = 0;
      for(int i = 0; i < dim; i++) {
         result += vec1[i] * vec2[i];
      }
      return result;
   }

   public static double length(double[] vec) {
      return Math.sqrt(dot(vec, vec));
   }
}



public class VectorDemo {

   public static void main(String[] args) {
      double[] v1 = {3, 4, 5};
      double[] v2 = {2, 1, -7};
      double[] v3 = VectorUtils.add(v1, v2);
      System.out.print("sum = ");
      VectorUtils.display(v3);
      System.out.println("dot = " + VectorUtils.dot(v1, v2));
      System.out.println("Length of v3 = " + VectorUtils.length(v3));
   }
}

Program Output

sum = < 5.0 5.0 -2.0 >
dot = -25.0
Length of v3 = 7.3484692283495345

 

Example: Statistics

class StatUtils {

   /** = avg */
   public static double mean(double[] data) {
      double result = 0;
      for(int i = 0; i < data.length; i++) {
         result += data[i];
      }
      return result/data.length;
   }

   public static double max(double[] data) {
      double result = Double.NEGATIVE_INFINITY;
      for(int i = 0; i < data.length; i++) {
         result = Math.max(result, data[i]);
      }
      return result;
   }

   /** = mean distance from mean */
   public static double standardDeviation(double[] data) {
      double mean = mean(data);
      double result = 0;
      for(int i = 0; i < data.length; i++) {
         result += (data[i] - mean) * (data[i] - mean);
      }
      result = result/(data.length - 1);
      result = Math.sqrt(result);
      return result;
   }
}



public class TestStatUtils {
   public static void main(String[] args) {
      double[] scores = new double[10];
      scores[0] = 87;
      scores[1] = 93;
      scores[2] = 64;
      scores[3] = 59;
      scores[4] = 70;
      scores[5] = 72;
      scores[6] = 75;
      scores[7] = 25;
      scores[8] = 80;
      scores[9] = 71;
      System.out.println("mean = " + StatUtils.mean(scores));
      System.out.println("max = " + StatUtils.max(scores));
      System.out.println("sd = " +
         StatUtils.standardDeviation(scores));
   }

}

Example: Polylines

Imports

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

Viewer

public class PolyViewer {

   public static final int FRAME_WIDTH = 300;
   public static final int FRAME_HEIGHT = 400;

   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setTitle("Frame Viewer");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      // create custom component:
      PolyComponent component = new PolyComponent(6, 50, 100, 200);
      frame.add(component);
      frame.setVisible(true);
   }
}

Component

class PolyComponent extends JComponent {

   private Polygon poly;

   public PolyComponent(int numVerts, int radius, int xc, int yc) {
      int[] x = new int[numVerts];
      int[] y = new int[numVerts];
      double angle = 2 * Math.PI/numVerts;
      for(int i = 0; i < numVerts; i++) {
         x[i] = (int)(xc + radius * Math.cos(i * angle));
         y[i] = (int)(yc + radius * Math.sin(i * angle));
      }
      poly = new Polygon(x, y, numVerts);
   }

   public void paintComponent(Graphics gc) {
      Graphics2D gc2d = (Graphics2D)gc;
      gc2d.draw(poly);
   }
}

Output

Example: Command Line Arguments

Assume the file Calc.java contains

public class Calc {
   public static void main(String[] args) {
     
   }
}

Recall how a Java program is compiled and run from a Windows or UNIX command console:

> javac Calc.java
> java Calc

The first line generates the file Calc.class. The second line starts the Java virtual machine (VM) and asks Calc to execute its main method:

Calc.main({});

Recall that main is static, so we don't need to first create a Calc object and ask it to execute main.

Note that main expects args, and array of String as input. The empty curly braces indicate that this array is empty.

However, if we append some additional strings to the second command console line:

> java Calc 23.1 + 42

The VM now asks Calc to execute its main method as follows:

Calc.main({"23.1", "+", "42"});

Inside main we can now access these additional command line arguments:

public class Calc {
   public static void main(String[] args) {
      for(int i = 0; i < args.length; i++) {
         System.out.println(args[i]);
      }
   }
}

Of course we could do something more significant:

public class Calc {
   public static void main(String[] args) {
      // do the arithmetic and display the result
   }
}

Array Algorithms

import java.util.*;

public class AlgorithmDemos {

   public static void test1() {
      int N = 10;
      int[] nums = new int[N];
      Random gen = new Random();
      for(int i = 0; i < N; i++) {
         nums[i] = gen.nextInt(100);
      }
      System.out.println(Arrays.toString(nums));
      int[] nums2 = Arrays.copyOf(nums, N);

      Arrays.sort(nums);
      System.out.println(Arrays.toString(nums));

      System.out.println("equals? = " + Arrays.equals(nums, nums2));
      Arrays.fill(nums, 100);
      System.out.println(Arrays.toString(nums));
   }

   public static void main(String[] args) {
      test1();
   }
}

Program Output

[47, 88, 94, 30, 54, 94, 37, 95, 72, 60]
[30, 37, 47, 54, 60, 72, 88, 94, 94, 95]
equals? = false
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]