Multi-Dimensional Arrays

Multi-Dimensional Arrays

Two dimensional arrays

  • Instantiation: Int[][] table = new int[3][4]; // declares an array with 3 rows and 4 columns
  • Accessing Elements: table[row][column] = 23;

Arrays of Arrays

  • In java, multidimensional arrays are in fact arrays of arrays.
  • Extracting a row of a table: int[][] table = new int[40][40]; int[] row1 = table[1];
  • Extracting a column is not so easy.

Nested Loops

 int[][] table = new int[10][6];
    for (int row=0; row<table.length; row++) {
        for (int column=0; column<table[row].length; column++) {
            System.out.printf("$%d ", table[row][column]);
        }
        System.out.println("");
    }

Higher than 2 dimensions

 int[][][][] table4D = new int[10][10][10][10]; // declares an array w/ 10,000 elements
  • access like:
 table4D[1][2][3][4];
 

Ragged Arrays

  • Arrays with rows of different lengths.

Enumerations

  • a way to define lists of constants public enum {CLUBS, DIAMONDS, HEARTS, SPADES} Suit s = Suit.DIAMONDS;

Assignment 3

  • We're making connect 4 as a console program!!!

Checks

4 checks: horizontal, vertical, both diagonals.

 for (row = 0; row < B.length; row++) {
        for (col = 0; col <= B[row].length; col++) {
            if (B[row][col] == B[row][col +1]).....&&
                                          +2 &&
                                          +3 &&
                    B[row][col] != ' ' ) {
                // WIN!! 
            }
        }
    }

Outline

public static void placePiece(int column, char[][] board, char piece)
public static boolean isLegalMove(int column, char[][] board)
public static void printBoard(char[][] board)
public static char playerWon(char[][] board)

Inheritance

What is Inherited?

  • A derived class inherits
    • Non-private variables and methods

Class Terms

Parent class -> Child class Superclass -> Subclass Base class -> Derived class Ancestor class -> blarg.

Overriding Methods

  • Overridden methods must have the same signature and return type.

Overriding vs. Overloading

  • Overloading
    • Two methods, same name, different signatures.
  • Overriding
    • A subclass re-implements the same function

Final Modifier

  • the ``final" modifier prevents a method from being overriden.
  • Final can also blarg.