2D Arrays are arrays of arrays. They are used to store a collection of related data - either primitives or objects. 2D arrays are organized into rows (horizontally) and columns (vertically).
A5
. So, in the example below, if I want to access the unit cost for espresso, I'd have to use cell reference B2
.a8
.With all of these examples, we can see that they are rectangular in their shape - i.e. in every row there is the same number of elements. While Java supports non-rectangular arrays (also known as jagged arrays), this is outside the scope of AP CS A.
The declaration should look as follows:
twodArrayName= new dataType[numberOfRows][numberOfColumns];
Examples:
ticketReservations = new boolean[20][15];
seatingChart = new String [6][4];
bitmapImage1= new Pixel [768][1024];
blackAndWhiteImage = new boolean [400][600];
testResultsbyQuestion = new int [20][35];
Remember that until you initialize the 2D array with values, it will be loaded with default values for primitives or with the null
reference for object data types.
Java stores 2D arrays as arrays of arrays. While doing so, it uses the so called row-major order (like in a spreadsheet, or a flat-file database) where each row is an array on its own. So, the 2D array is an array of rows. It first saves the data in the first row of the table in an array, then proceeds to the 2nd row, etc.
In some programming languages the so-called column-major order is used. This is where each column would be stored as a separate array. So the 2D array would be an array of columns - it would first save all data in the first column in an array and then proceed to the next column.
Let's consider the following example:
testScores
stores the individual scores for questions on a 4-question test. We have data available for four students. Each student's scores are recorded in one row:In order to see, how the first student did on the second question, I'd have to access the following element: testScores[0][1]
.
Please, note, that just like with 1D arrays, 2D array indexes start from 0, not 1.
You can set the values in a 2D array individually:
testScores[1][3]=1;
This sets the score on the fourth question for the second student to 1
.
You can also populate a 2D array using a bulk command - the so called initializer list:
String [][] seatingChart = {{"Andy","Anton","Anthony"},{"Aldiyar","Wonkyu","Tomas"}};
Please notice that each row is enclosed in curly brackets and separated by a comma from the next row.
It is analogous to 1D array data retrieval:
String name = seatingChart[1][0]; //prints "Aldiyar"