Home

Multidimensional Arrays

 

Fundamentals of Multidimensional Arrays

 
 

Introduction

The arrays we used so far were made of a uniform series, where all members consisted of a simple list, like a column of names on a piece of paper. Also, all items fit in one list. This type of array is referred to as one-dimensional.

In some cases, you may want to divide the list in delimited sections. For example, if you create a list of names, you may want part of the list to include family members and another part of the list to include friends. Instead of creating a second list, you can add a second dimension to the list. In other words, you would create a list of a list, or one list inside of another list, although the list is still made of items with common characteristics.

A multidimensional array is a series of arrays so that each array contains its own sub-array(s).

Practical LearningPractical Learning: Introducing Multidimensional Arrays

  1. Start NetBeans
  2. Create a new Java Application named DepartmentStore5
  3. Change the Main.java file as follows:
     
    package departmentstore5;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            long itemID = 0;
            double price = 0.00d;
            String description = "Unknown";
                
            System.out.println("Item Identification");
            System.out.println("Item Number: " + itemID);
            System.out.println("Description: " + description);
            System.out.printf("Unit Price:  %.2f\n", price);
        }
    }
  4. Execute the application to see the result. This would produce:
     
    Receipt
    Item Number: 0
    Description: Unknown
    Unit Price:  $0.00

Creating a Two-Dimensional Array

The most basic multidimensional array is made of two dimensions. This is referred to as two-dimensional.  To create a two-dimensional array, inside of one pair of square brackets, use two pairs (of square brackets). The formula you would use is:

DataType[][] VariableName;

Although the pairs of brackets are empty, they will contain some numbers. There are various ways you can initialize a two-dimensional array. If you are declaring the array variable but are not ready to initialize it, use the following formula:

DataType[][] VariableName = new DataType[Number1][Number2];

In Java, you can place the first square brackets on the right side of the name of the variable:

DataType VariableName[][] = new DataType[Number1][Number2];

In the square brackets on the right side of the = operator, enter an integer in each. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];
    }
}

In our declaration, the members variable contains two lists. Each of the two lists contains 4 elements. This means that the first list contains 4 elements and the second list contains 4 elements. Therefore, the whole list is made of 8 elements (2 * 4 = 8). Because the variable is declared as a String, each of the 8 items must be a string.

You can also create a two-dimensional array that takes more than two lists, such as 3, 4, 5 or more. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][8];
    }
}

This time, the variable is a 2-dimensional (2 lists) array where each list contains 8 components. This means that the whole array contains 2 * 8 = 16 components.

If you want to declare the array variable using the first formula where you do not know the sizes of the lists, you must use the data type of the array and you can omit the right square brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String members[][];
    }
}

Initializing a Two-Dimensional Array

There are various ways you can initialize a multidimensional array. You can initialize an array variable when declaring it. To do this, on the right side of the declaration, do not include the values in the square brackets:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] Members = new String[][] . . . ;
    }
}

Before the closing semi-colon, type an opening and a closing curly brackets. Inside of the brackets, include a pair of an opening and a closing curly brackets for each internal array. Then, inside of a pair of curly brackets, provide a list of the values of the internal array, just as you would do for a one-dimensional array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] Members = new String[][] {
	    { "Celeste", "Mathurin", "Alex", "Germain" },   // First List
	    { "Jeremy", "Mathew", "Anselme", "Frederique" } // Second List
        };
    }
}

Practical Learning Practical Learning: Creating a Two-Dimensional Array

  1. To create and use a two-dimensional array, change the file as follows:
     
    package departmentstore5;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            long itemID = 0;
            double price = 0.00d;
            String description = "Unknown";
    
            // The first list contains women's items
            // The other contains non-women items
            long[][] itemNumbers = new long[][] {
                { 947783, 934687, 973947, 987598, 974937 },
                { 739579, 367583, 743937, 437657, 467945 } };
                
            String[][] itemNames = new String[][] {
                {
                    "Women Double-faced wool coat",
                    "Women Floral Silk Tank Blouse",
                    "Women Push Up Bra",
                    "Women Chiffon Blouse",
                    "Women Bow Belt Skirtsuit"
                },
                {
                    "Men Cotton Polo Shirt",
                    "Children Cable-knit Sweater  ",
                    "Children Bear Coverall Cotton",
    	        "Baby three-piece Set         ",
    	        "Girls Jeans with Heart Belt  "
                }
            };
    
            double[][] unitPrices = new double[][] {
                { 275.25D, 180.05D, 50.00D, 265.35D, 245.55D },
    	    {  45.55D,  25.65D, 28.25D,  48.55D,  19.95D }
            };
            
            System.out.println("Item Identification");
            System.out.println("Item Number: " + itemID);
            System.out.println("Description: " + description);
            System.out.printf("Unit Price:  %.2f\n", price);
        }
    }
  2. Save the file

Accessing the Members of a Two-Dimensional Array

To use the members of a two-dimensional array, you can access each item individually. For example, to initialize a two-dimensional array, you can access each member of the array and assign it a value. The external list is zero-based. In other words, the first list has an index of 0, the second list has an index of 1. Internally, each list is zero-based and behaves exactly like a one-dimensional array.

To access a member of the list, type the name of the variable followed by the square brackets. In the left brackets, type the index of the list. In the right square brackets, type the index of the component inside the internal list, the member whose access you need. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];

        members[0][0] = "Celeste";    // Member of the First List
        members[0][1] = "Mathurin";   // Member of the First List
        members[0][2] = "Alex";       // Member of the First List
        members[0][3] = "Germain";    // Member of the First List
        members[1][0] = "Jeremy";     // Member of the Second List
        members[1][1] = "Mathew";     // Member of the Second List
        members[1][2] = "Anselme";    // Member of the Second List
        members[1][3] = "Frederique"; // Member of the Second List
    }
}

You can use this same technique to retrieve the value of each member of the array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];

        members[0][0] = "Celeste";    // Member of the First List
        members[0][1] = "Mathurin";   // Member of the First List
        members[0][2] = "Alex";       // Member of the First List
        members[0][3] = "Germain";    // Member of the First List
        members[1][0] = "Jeremy";     // Member of the Second List
        members[1][1] = "Mathew";     // Member of the Second List
        members[1][2] = "Anselme";    // Member of the Second List
        members[1][3] = "Frederique"; // Member of the Second List

        System.out.println(members[0][0]);
        System.out.println(members[0][1]);
        System.out.println(members[0][2]);
        System.out.println(members[0][3]);
        System.out.println(members[1][0]);
        System.out.println(members[1][1]);
        System.out.println(members[1][2]);
        System.out.println(members[1][3]);
    }
}

This would produce:

Celeste
Mathurin
Alex
Germain
Jeremy
Mathew
Anselme
Frederique

As we described it earlier, a two-dimensional array is a list of two arrays, or two arrays of arrays. In other words, the second arrays are nested in the first arrays. In the same way, if you want to access them using a loop, you can nest one for loop inside of a first for loop. The external loop accesses a member of the main array and the second loop accesses the internal list of the current array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        String[][] members = new String[2][4];

        members[0][0] = "Celeste";    // Member of the First List
        members[0][1] = "Mathurin";   // Member of the First List
        members[0][2] = "Alex";       // Member of the First List
        members[0][3] = "Germain";    // Member of the First List
        members[1][0] = "Jeremy";     // Member of the Second List
        members[1][1] = "Mathew";     // Member of the Second List
        members[1][2] = "Anselme";    // Member of the Second List
        members[1][3] = "Frederique"; // Member of the Second List

	for (int external = 0; external < 2; external++)
            for (int internal = 0; internal < 4; internal++)
                System.out.println(members[external][internal]);
    }
}

Practical LearningPractical Learning: Accessing the Members

  1. To retrieve the values of a two-dimensional array, change the file as follows:
     
    package departmentstore5;
    import java.io.*;
    import java.util.InputMismatchException;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            long itemID = 0;
            double price = 0.00d;
            boolean itemFound = false;
            String description = "Unknown";
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(System.in));
    
            // The first list contains women's items
            // The other contains non-women items
            long[][] itemNumbers = new long[][] {
                { 947783, 934687, 973947, 987598, 974937 },
                { 739579, 367583, 743937, 437657, 467945 } };
                
            String[][] itemNames = new String[][] {
                {
                    "Women Double-faced wool coat",
                    "Women Floral Silk Tank Blouse",
                    "Women Push Up Bra",
                    "Women Chiffon Blouse",
                    "Women Bow Belt Skirtsuit"
                },
                {
                    "Men Cotton Polo Shirt",
                    "Children Cable-knit Sweater  ",
                    "Children Bear Coverall Cotton",
    	        "Baby three-piece Set         ",
    	        "Girls Jeans with Heart Belt  "
                }
            };
    
            double[][] unitPrices = new double[][] {
                { 275.25D, 180.05D, 50.00D, 265.35D, 245.55D },
    	    {  45.55D,  25.65D, 28.25D,  48.55D,  19.95D }
            };
    
            // Order Processing
            try {
                System.out.print("Enter Item Number: ");
                    itemID = Long.parseLong(br.readLine());
            }
            catch(InputMismatchException ime) {
                System.out.println("Invalid Number - The program will terminate");   
            }
    
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 5; j++) {
                    if (itemID == itemNumbers[i][j]) {
                        description = itemNames[i][j];
                        price = unitPrices[i][j];
                        itemFound = true;
                    }
                }
            }
            
            if( itemFound == true ) {
                System.out.println("Item Identification");
                System.out.println("Item Number: " + itemID);
                System.out.println("Description: " + description);
                System.out.printf("Unit Price:  %.2f\n", price);
            }
            else
                System.out.println("No item with that number was found.");
            
        }
    }
  2. Execute the application and test it. Here is an example:
     
    Enter Item Number: 367582
    No item with that number was found.
  3. Execute the application again and enter a different item number. Here is an example:
     
    Enter Item Number: 367583
    Item Identification
    Item Number: 367583
    Description: Children Cable-knit Sweater  
    Unit Price:  25.65

Multidimensional Arrays

 

Introduction

Beyond two dimensions, you can create an array variable that represents various lists, each list would contain various internal lists, and each internal list would contain its own components. This is referred to as a multidimensional array. One of the rules you must follow is that, as always, all members of the array must be of the same type.

Creating a Multidimensional Array

To create a multidimensional array, add as many pairs of square brackets you need. If you only want to declare the variable without indicating the actual number of lists, you can specify the data type followed by square brackets. Here is an example that represents a three-dimensional array that is not initialized:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers;
    }
}

If you know the types of members the array will use, you can use the assignment operator and specify the numbers of lists in the square brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers = new double[2][3][5];
    }
}

In this example, we are creating 2 groups of items. Each of the two groups is made of three lists. Each list contains 5 numbers. As a result, the array contains 2 * 3 * 5 = 30 components. To better understand this, consider that the left square brackets represent a page in a book, the middle square brackets represent a table drawn on the page, and the right square brackets represent each item in the table.

Initializing a Multidimensional Array

As always, there are various ways you can initialize an array. To initialize a multidimensional array when creating it, you use a pair of curly brackets for each list. The most left pair of curly brackets represents the main array (a page in the book). After the left curly brackets, the second curly brackets represent an inside list (like a table in a page). The right square brackets represent the actual items in the array. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers = new double[][][]	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
		{-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    }
	};
    }
}

Accessing the Members of a Multidimensional Array

To access a member of a multidimensional array, type the name of the array followed by the necessary square brackets. In the left square brackets, type the external index (the page of a book). In the second square brackets, type the index of the list. In the last square brackets, type the index of the item you want to access. After doing this, you can assign a value to the item. Here are examples:

public class Exercise {
    public static void main(String[] args) throws Exception {
        double[][][] numbers = new double[2][3][5];
	
	numbers[0][0][0] = 12.44;
	numbers[0][1][1] = 525.38;
	numbers[0][2][2] = -6.28;
	numbers[0][0][3] = 2448.32;
	numbers[0][1][4] = 632.04;
	numbers[0][2][0] = -378.05;
	numbers[0][0][1] = 48.14;
	numbers[0][1][2] = 634.18;
	numbers[0][2][3] = 762.48;
	numbers[0][0][4] = 83.02;
	numbers[0][1][0] = 64.92;
	numbers[0][2][1] = -7.44;
	numbers[0][0][2] = 86.74;
	numbers[0][1][3] = -534.60;
	numbers[0][2][4] = 386.73;
	numbers[1][0][0] = 48.02;
	numbers[1][1][1] = 120.44;
	numbers[1][2][2] = 38.62;
	numbers[1][0][3] = 526.82;
	numbers[1][1][4] = 1704.62;
	numbers[1][2][0] = 56.85;
	numbers[1][0][1] = 105.48;
	numbers[1][1][2] = 363.31;
	numbers[1][2][3] = 172.62;
	numbers[1][0][4] = 128.48;
	numbers[1][1][0] = 906.68;
	numbers[1][2][1] = 47.12;
	numbers[1][0][2] = -166.07;
	numbers[1][1][3] = 4444.26;
	numbers[1][2][4] = 408.62;
    }
}

This is the same approach you can use to access each member of the array to check or retrieve its value. Here are examples:

public class Exercise {
    public static void main(String[] args) throws Exception {
	double[][][] numbers = new double[][][]	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
		{-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    }
	};

        System.out.println("numbers[0][0][0] = " + numbers[0][0][0]);
        System.out.println("numbers[0][0][1] = " + numbers[0][0][1]);
        System.out.println("numbers[0][0][2] = " + numbers[0][0][2]);
        System.out.println("numbers[0][0][3] = " + numbers[0][0][3]);
        System.out.println("numbers[0][0][4] = " + numbers[0][0][4]);

        System.out.println("\nnumbers[0][1][0] = " + numbers[0][1][0]);
        System.out.println("numbers[0][1][1] = " + numbers[0][1][1]);
        System.out.println("numbers[0][1][2] = " + numbers[0][1][2]);
        System.out.println("numbers[0][1][3] = " + numbers[0][1][3]);
        System.out.println("numbers[0][1][4] = " + numbers[0][1][4]);

        System.out.println("\nnumbers[0][2][0] = " + numbers[0][2][0]);
        System.out.println("numbers[0][2][1] = " + numbers[0][2][1]);
        System.out.println("numbers[0][2][2] = " + numbers[0][2][2]);
        System.out.println("numbers[0][2][3] = " + numbers[0][2][3]);
        System.out.println("numbers[0][2][4] = " + numbers[0][2][4]);

        System.out.println("\nnumbers[1][0][0] = " + numbers[1][0][0]);
        System.out.println("numbers[1][0][1] = " + numbers[1][0][1]);
        System.out.println("numbers[1][0][2] = " + numbers[1][0][2]);
        System.out.println("numbers[1][0][3] = " + numbers[1][0][3]);
        System.out.println("numbers[1][0][4] = " + numbers[1][0][4]);

        System.out.println("\nnumbers[1][1][0] = " + numbers[1][1][0]);
        System.out.println("numbers[1][1][1] = " + numbers[1][1][1]);
        System.out.println("numbers[1][1][2] = " + numbers[1][1][2]);
        System.out.println("numbers[1][1][3] = " + numbers[1][1][3]);
        System.out.println("numbers[1][1][4] = " + numbers[1][1][4]);

        System.out.println("\nnumbers[1][2][0] = " + numbers[1][2][0]);
        System.out.println("numbers[1][2][1] = " + numbers[1][2][1]);
        System.out.println("numbers[1][2][2] = " + numbers[1][2][2]);
        System.out.println("numbers[1][2][3] = " + numbers[1][2][3]);
        System.out.println("numbers[1][2][4] = " + numbers[1][2][4]);
    }
}

This would produce:

Number[0][0][0] = 12.44
Number[0][0][1] = 525.38
Number[0][0][2] = -6.28
Number[0][0][3] = 2448.32
Number[0][0][4] = 632.04

Number[0][1][0] = -378.05
Number[0][1][1] = 48.14
Number[0][1][2] = 634.18
Number[0][1][3] = 762.48
Number[0][1][4] = 83.02

Number[0][2][0] = 64.92
Number[0][2][1] = -7.44
Number[0][2][2] = 86.74
Number[0][2][3] = -534.6
Number[0][2][4] = 386.73

Number[1][0][0] = 48.02
Number[1][0][1] = 120.44
Number[1][0][2] = 38.62
Number[1][0][3] = 526.82
Number[1][0][4] = 1704.62

Number[1][1][0] = 56.85
Number[1][1][1] = 105.48
Number[1][1][2] = 363.31
Number[1][1][3] = 172.62
Number[1][1][4] = 128.48

Number[1][2][0] = 906.68
Number[1][2][1] = 47.12
Number[1][2][2] = -166.07
Number[1][2][3] = 4444.26
Number[1][2][4] = 408.62

Since the lists are nested, if you want to use loops to access the members of the array, you can nest the for loops to incrementally access the values. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	double[][][] numbers = new double[][][]	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
		{-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    }
	};

	for(int page = 0; page < 2; page++)
            for(int table = 0; table < 3; table++)
                for(int value = 0; value < 5; value++)
        	    System.out.println("Number = " +
			numbers[page][table][value]);
    }
}

This would produce:

Number = 12.44
Number = 525.38
Number = -6.28
Number = 2448.32
Number = 632.04
Number = -378.05
Number = 48.14
Number = 634.18
Number = 762.48
Number = 83.02
Number = 64.92
Number = -7.44
Number = 86.74
Number = -534.6
Number = 386.73
Number = 48.02
Number = 120.44
Number = 38.62
Number = 526.82
Number = 1704.62
Number = 56.85
Number = 105.48
Number = 363.31
Number = 172.62
Number = 128.48
Number = 906.68
Number = 47.12
Number = -166.07
Number = 4444.26
Number = 408.62
 
 

 

 

Multidimensional Arrays and Classes

 

Introduction

Like an array of a primitive type, a multidimensional array can be made a field of a class. You can primarily declare it without initializing it. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] points;
}

This indicates a two-dimensional array field: the array will contain two lists but we don't know (yet) how many members each array will contain. Therefore, if you want, when creating the array, you can specify its dimension by assigning it a second pair of square brackets using the new operator and the data type. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] points = new int[3][2];
}

You can also use a method of the class or a constructor to indicate the size of the array. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] points;

    public TriangleInCoordinateSystem() {
        points = new int[3][2];
    }
}

To initialize the array, you can access each member using the square brackets as we saw in the previous sections. Here is an example:

public class TriangleInCoordinateSystem {
    private int[][] Points;

    public TriangleInCoordinateSystem() {
        Points = new int[3][2];

        points[0][0] = -2; // A(x, )
        points[0][1] = -3; // A( , y)
        points[1][0] =  5; // B(x, )
        points[1][1] =  1; // B( , y)
        points[2][0] =  4; // C(x, )
        points[2][1] = -2; // C( , y)
    }
}

After initializing the array, you can use it as you see fit. For example, you can display its values to the user. Here is an example:

class TriangleInCoordinateSystem {
    private int[][] points;

    public TriangleInCoordinateSystem() {
        points = new int[3][2];

        points[0][0] = -2; // A(x, )
        points[0][1] = -3; // A( , y)
        points[1][0] =  5; // B(x, )
        points[1][1] =  1; // B( , y)
        points[2][0] =  4; // C(x, )
        points[2][1] = -2; // C( , y)
    }

    public void showPoints() {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", points[0][0], points[0][1]);
        System.out.printf("B(%d, %d)\n", points[1][0], points[1][1]);
        System.out.printf("C(%d, %d)", points[2][0], points[2][1]);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	TriangleInCoordinateSystem triangle = new TriangleInCoordinateSystem();

        triangle.showPoints();
    }
}

This would produce:

Coordinates of the Triangle
A(-2, -3)
B(5, 1)
C(4, -2)

A Multidimensional Array as Argument

A multidimensional array can be passed as argument. When creating the method, in its parentheses, enter the data type followed by the necessary number of combinations of square brackets. Here is an example:

public class TriangleInCoordinateSystem {
    public void showPoints(int[][] Coords) {
    }
}

When defining the method, in its body, you can use the array as you see fit, such as displaying its values. Here is an example:

public class TriangleInCoordinateSystem {
    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

To call this type of method, pass only the name of the array. Here is an example:

class TriangleInCoordinateSystem {
    public TriangleInCoordinateSystem() {
    }

    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
        int points[][] = new int[3][2];

        points[0][0] = -2; // A(x, )
        points[0][1] = -3; // A( , y)
        points[1][0] =  5; // B(x, )
        points[1][1] =  1; // B( , y)
        points[2][0] =  4; // C(x, )
        points[2][1] = -2; // C( , y)

	TriangleInCoordinateSystem triangle = new TriangleInCoordinateSystem();

        triangle.showPoints(points);
    }
}

As indicated with one-dimensional arrays, when passing an multi-dimensional array as argument, the array is treated as a reference. This makes it possible for the method to modify the array and return it changed. Here is an example:

class TriangleInCoordinateSystem {
    public void createPoints(int[][] coords) {
        coords[0][0] = -2; // A(x, )
        coords[0][1] = -3; // A( , y)
        coords[1][0] =  5; // B(x, )
        coords[1][1] =  1; // B( , y)
        coords[2][0] =  4; // C(x, )
        coords[2][1] = -2; // C( , y)
    }

    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	int points[][] = new int[3][2];

	TriangleInCoordinateSystem triangle =
		new TriangleInCoordinateSystem();
	triangle.createPoints(points);
        triangle.showPoints(points);
    }
}

Returning a Multidimensional Array

You can return a multi-dimensional array from a method. When creating the method, before its name, specify the data type followed by the multidimensional combination of square brackets. Here is an example:

public class TriangleInCoordinateSystem {
    public int[][] CreateTriangle() {
    }
}

In the body of the method, you can do what you want but, before exiting it, you must return an array of the same type that was created. Here is an example:

class TriangleInCoordinateSystem {
    public int[][] CreateTriangle() {
	int[][] values = new int[3][2];
	return values;
    }
}

When calling the method, you can assign it to an array of the same type it returns. Here is an example:

class TriangleInCoordinateSystem {
    public int[][] createTriangle() {
	int[][] values = new int[3][2];
    
        values[0][0] = 6; // A(x, )
        values[0][1] = 1; // A( , y)
        values[1][0] = 2; // B(x, )
        values[1][1] = 3; // B( , y)
        values[2][0] = 1; // C(x, )
        values[2][1] = 4; // C( , y)

	return values;
    }

    public void showPoints(int[][] pts) {
        System.out.println("Coordinates of the Triangle");
        System.out.printf("A(%d, %d)\n", pts[0][0], pts[0][1]);
        System.out.printf("B(%d, %d)\n", pts[1][0], pts[1][1]);
        System.out.printf("C(%d, %d)", pts[2][0], pts[2][1]);
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	int[][] coordinates = new int[3][2];

        TriangleInCoordinateSystem triangle = new TriangleInCoordinateSystem();

        coordinates = triangle.createTriangle();
        triangle.showPoints(coordinates);
    }
}

This would produce:

Coordinates of the Triangle
A(6, 1)
B(2, 3)
C(1, 4)

A Multidimensional Array of Objects

 

A Variable of a Multidimensional Array of Objects

As done for primitive data types, you can create a multi-dimensional array where each component is of a class type. Of course, you can use an existing class or you must first create a class. Here is an example:

public class Point {
    private int xCoord;
    private int yCoord;

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

To create a multidimensional array of objects without initializing it, you can use the following formula:

ClassName[][] VariableName;

If you know the number of instances of the class that the array will use, you can use the following formula:

ClassName[][] VariableName = new ClassName[Number1][Number2];

Remember that you can position the square brackets after the name of the variable:

ClassName VariableName[][] = new ClassName[Number1][Number2];

The ClassName factor is the name of the class that will make up each component of the array. The other sections follow the same rules we reviewed for the primitive types. For example, you can create an array without allocating memory for it as follows:

class Point {
    private int xCoord;
    private int yCoord;

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line;
    }
}

If you know the number of components that the array will contain, you can use the right pair of square brackets, in which case you can specify the name of the class and the square brackets. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[2][2];
    }
}

This declaration creates a two-dimensional array of two Point objects: The array contains two lists and each list contains two Points.

To initialize a multidimensional array of objects, you can access each array member using its index, allocate memory for it using the new operator. After allocating memory for the member, you can then access its fields or methods to initialize it. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[2][2];

        line[0][0] = new Point(); // First Point A
        line[0][0].setX(-3);      // A(x,  )
        line[0][0].setY(8);       // A( , y)

        line[0][1] = new Point(); // Second Point B
        line[0][1].setX(4);       // B(x,  )
        line[0][1].setY(-5);      // B( , y)
    }
}

You can also initialize the array when creating it. Before doing this, you would need a constructor of the class and the constructor must take the argument(s) that would be used to initialize each member of the array. To actually initialize the array, you would need a pair of external curly brackets for the main array. Inside of the external curly brackets, create a pair of curly brackets for each sub-dimension of the array. Inside the last curly brackets, use the new operator to access an instance of the class and call its constructor to specify the values of the instance of the class. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };
    }
}

Accessing the Members of a Multidimensional Array of Objects

To access the members of a multidimensional array of objects, apply the square brackets to a particular member of the array and access the desired field or method of the class. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };

	System.out.println("Line =-=");
        System.out.printf("From A(%d, %d) to B(%d, %d)",
                          line[0][0].getX(), line[0][0].getY(),
                          line[0][1].getX(), line[0][1].getY());
    }
}

This would produce:

Line =-=
From A(-3, 8) to B(4, -5)

You can also use a loop to access the members of the array. To do this, create a first for loop that stops at the first dimension of the array - 1. Then, inside of a first for loop, nest a for loop for each subsequent dimension. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };

	System.out.println("The points of the line are:");
        for(int i = 0; i < 1; i++)
            for(int j = 0; j < 2; j++)
                System.out.printf("(%d, %d)\n",
                          line[i][j].getX(), line[i][j].getY());
    }
}

This would produce:

The points of the line are:
(-3, 8)
(4, -5)

To apply a for each operator, access only each member of the internal list. Here is an example:

public class Exercise {
    public static void main(String[] args) throws Exception {
	Point[][] line = new Point[][] {
	    {
		new Point(-3, 8),
		new Point(4, -5)
	    }
        };

	System.out.println("The points of the line are:");
	for(Point pts : line[0])
            System.out.printf("(%d, %d)\n",
                          pts.getX(), pts.getY());
    }
}

Multidimensional Arrays of Objects and Classes

 

Introduction

As done for primitive types, a multidimensional array of objects can be made a field of a class. You can declare the array without specifying its size. Here is an example:

public class Triangle {
    public Point[][] vertices;
}

If you know the dimensions that the array will have, you can specify them using the new operator at the same time you are creating the field. Here is an example:

public class Triangle {
    public Point[][] vertices = new Point[3][2];
}

This creation signals a multidimensional array of Point objects. It will consist of three lists and each list will contain two Point objects

To initialize the array, access each member by its index to allocate memory for it. Once you get the member, you access each one of its fields or properties and initialize it with the desired value. Here is an example:

public class Triangle {
    public Point[][] Vertices = new Point[3][2];

    public Triangle() {
        vertices[0][0] = new Point(); // Point A(x, y)
        vertices[0][0].setX(-2);      // A(x,  )
        vertices[0][0].setY(-4);      // A( , y)
        vertices[1][0] = new Point(); // Point B(x, y)
        vertices[1][0].setX(3);       // B(x,  )
        vertices[1][0].setY(5);       // B( , y)
        vertices[2][0] = new Point(); // Point C(x, y)
        vertices[2][0].setX(6);       // C(x,  )
        vertices[2][0].setY(-2);      // C( , y)
    }
}

If the class is equipped with the right constructor, you can use it to initialize each member of the array.

Once the array is ready, you can access each members using its index and manipulate it. For example you can display its value(s) to the user. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public Point() {
        xCoord = 0;
        yCoord = 0;
    }
    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

class Triangle {
    public Point[][] vertices = new Point[3][2];

    public Triangle() {
        vertices[0][0] = new Point(); // Point A(x, y)
        vertices[0][0].setX(-2);      // A(x,  )
        vertices[0][0].setY(-4);      // A( , y)
        vertices[1][0] = new Point(); // Point B(x, y)
        vertices[1][0].setX(3);       // B(x,  )
        vertices[1][0].setY(5);       // B( , y)
        vertices[2][0] = new Point(); // Point C(x, y)
        vertices[2][0].setX(6);       // C(x,  )
        vertices[2][0].setY(-2);      // C( , y)
    }

    public void identify() {
        System.out.print("Triangle Vertices: ");
        System.out.printf("A(%d, %d),  B(%d, %d), and C(%d, %d)",
                          vertices[0][0].getX(), vertices[0][0].getY(),
                          vertices[1][0].getX(), vertices[1][0].getY(),
                          vertices[2][0].getX(), vertices[2][0].getY());
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Triangle tri = new Triangle();
        tri.identify();
    }
}

This would produce:

Triangle Vertices: A(-2, -4),  B(3, 5), and C(6, -2)

Passing a Multidimensional Array of Objects

You can pass a multidimensional array of objects as arguments. To do this, in the parentheses of the method, enter the class name followed by the appropriate combination of square brackets. Here is an example:

public class Triangle {
    public void create(Point[][] Points) {
    }
}

In the body of the method, use the array as you we have done so far. You can access its members to get to its values. Here are examples:

class Point {
    private int xCoord;
    private int yCoord;

    public Point() {
        xCoord = 0;
        yCoord = 0;
    }
    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

class Triangle {
    public void create(Point[][] points) {
        points[0][0] = new Point(); // Point A(x, y)
        points[0][0].setX(-2);      // A(x,  )
        points[0][0].setY(-4);      // A( , y)
        points[1][0] = new Point(); // Point B(x, y)
        points[1][0].setX(3);       // B(x,  )
        points[1][0].setY(5);       // B( , y)
        points[2][0] = new Point(); // Point C(x, y)
        points[2][0].setX(6);       // C(x,  )
        points[2][0].setY(-2);      // C( , y)
    }

    public void identify(Point[][] coords) {
        System.out.print("Triangle Vertices: ");
        System.out.printf("A(%d, %d),  B(%d, %d), and C(%d, %d)",
                          coords[0][0].getX(), coords[0][0].getY(),
                          coords[1][0].getX(), coords[1][0].getY(),
                          coords[2][0].getX(), coords[2][0].getY());
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Triangle tri = new Triangle();
	Point vertices[][] = new Point[3][2];

	tri.create(vertices);
        tri.identify(vertices);
    }
}

Remember that an array passed as argument is in fact passed by reference.

Returning a Multidimensional Array of Objects

A method can return a multidimensional array of objects. If you are creating the method, before its name, type the name of the class followed by the desired combination of square brackets. Here is an example:

public class Triangle {
    public Point[][] create() {
    }
}

After implementing the method, before exiting it, make sure it returns the type of array that it was indicated to produce. Here is an example:

class Point {
    private int xCoord;
    private int yCoord;

    public Point() {
        xCoord = 0;
        yCoord = 0;
    }
    public Point(int x, int y) {
        xCoord = x;
        yCoord = y;
    }

    public int getX() {
	return xCoord;
    }
    
    public void setX(int x) {
	xCoord = x;
    }

    public int getY() {
	return yCoord;
    }

    public void setY(int y) {
	yCoord = y;
    }
}

class Triangle {
    public Point[][] create() {
	Point[][] points = new Point[3][2];
        points[0][0] = new Point(); // Point A(x, y)
        points[0][0].setX(4);       // A(x,  )
        points[0][0].setY(8);       // A( , y)
        points[1][0] = new Point(); // Point B(x, y)
        points[1][0].setX(2);       // B(x,  )
        points[1][0].setY(-1);      // B( , y)
        points[2][0] = new Point(); // Point C(x, y)
        points[2][0].setX(3);       // C(x,  )
        points[2][0].setY(0);       // C( , y)

	return points;
    }

    public void identify(Point[][] coords) {
        System.out.print("Triangle Vertices: ");
        System.out.printf("A(%d, %d),  B(%d, %d), and C(%d, %d)",
                          coords[0][0].getX(), coords[0][0].getY(),
                          coords[1][0].getX(), coords[1][0].getY(),
                          coords[2][0].getX(), coords[2][0].getY());
    }
}

public class Exercise {
    public static void main(String[] args) throws Exception {
	Triangle tri = new Triangle();

	Point vertices[][] = tri.create();

        tri.identify(vertices);
    }
}

This would produce:

Triangle Vertices: A(4, 8),  B(2, -1), and C(3, 0)

 

 
 
 
 

Previous Copyright © 2009-2012, FunctionX, Inc. Next