Two dimensional Array - How to represent two-dimensional (2D) data ( table / grid ) in Java?
Two dimensional Array - How to represent two-dimensional (2D) data ( table / grid ) in Java?
This article is part of a tutorial.
Tutorial Index page - Java Data Modelling
1. Introduction
Every element in the data set has two parameters / properties. Examples of day to day two-dimensional data strutures include a table, a grid, a martix etc.
1.1. Example
For ease of understanding lets consider a simple two-dimensional data-set - a table
Col 1 |
Col 2 |
Col 3 |
|
Row 1 |
1 |
2 |
3 |
Row 2 |
3 |
1 |
2 |
Row 3 |
2 |
3 |
1 |
Here, the two-dimensions of every element in the data-set are the row and column.
2. Using two-dimensional arrays.
2.1. Introduction
"An array is a container object that holds a fixed number of values of a single type. Each item in an array is called an element, and each element is accessed by its numerical index." A two-dimensional array is one where each element is accessed by its two numerical indices.
The first step in using arrays is the initialisation bit. An important point to note about arrays is that you should specify the size of the array (only the row size is mandatory for 2-d arrays) during initialisation and that this size cannot be changed after array creation.
2.2. Initialisation
int[][] tableData = new int[3][3];
The above code initialises a 2-dimensional int array with 3 rows and 3 columns. An alternate way to initialise a 2-d array if you know its connect before hand is by...
int[][] tableData = new int[][] { {1, 2, 3}, {3, 1, 2}, {2, 3, 1} };
2.3. Populating with data
Now lets populate it with the values from the above table.
int[][] tableData = new int[3][3]; // Row 0 Col 0 tableData [0][0] = 1; // Row 0 Col 1 tableData [0][1] = 2; // Row 0 Col 2 tableData [0][2] = 3; // Row 1 Col 0 tableData [0][0] = 3; // Row 1 Col 1 tableData [0][1] = 1; // Row 1 Col 2 tableData [0][2] = 2; // Row 2 Col 0 tableData [0][0] = 2; // Row 2 Col 1 tableData [0][1] = 3; // Row 2 Col 2 tableData [0][2] = 1;
2.3. Retrieving data
If you feel it was easy so far, then its get even more easier when it comes to extracting values out of the populated array. To retrieve a value at a given row and column you can just do
int tableValue = twoDArray[1][1];
To retrive all the values from a two-dimensional array your can use a for-loop.
for (int row = 0; row < twoDArray.length; row++) { int[] tableRow = twoDArray[row]; for (int col = 0; col < tableRow.length; col++) { int tableValue = tableRow[col]; System.out.println("The table value at row - '" + row + "' col - " + col + " is " + tableValue); } }
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
