TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java 2D Array Examples

Use 2D arrays and jagged arrays. Initialize arrays and assign elements.
2D array. Not all elements come in linear order, one after another. Some have spatial relationships on a two-dimensional plane, a grid. We use 2D arrays to represent this.
Initializers. The syntax of 2D arrays is often complex. Two integer indexes locate a point in a 2D array. And with initializers, we quickly create these arrays.
Array example. To understand 2D arrays, we need to review several steps. The syntax for 2D arrays uses 2 values to address an element.

Step 1: We introduce a two-dimensional array of width 4 and height 4—a little square.

Step 2: We assign some elements with the array at indexes (two are required, an X and a Y).

Step 3: Here we loop over the top-level elements in a for-loop—each element itself contains another array.

Step 4: We use the subarrays like a one-dimensional array containing int values. We have an array of equal-length arrays.

Java program that uses 2D array public class Program { public static void main(String[] args) { // Step 1: create 2-dimensional array. int[][] values = new int[4][4]; // Step 2: assign three elements in it. values[0][0] = 1; values[1][1] = 2; values[3][2] = 3; // Step 3: loop over top-level arrays. for (int i = 0; i < values.length; i++) { // Step 4: loop and display sub-arrays. int[] sub = values[i]; for (int x = 0; x < sub.length; x++) { System.out.print(sub[x] + " "); } System.out.println(); } } } Output 1 0 0 0 0 2 0 0 0 0 0 0 0 0 3 0
Array initializers. With these, we fill a newly-declared array with constant values. Here I create another little square, this time 2 by 2, with the values one through 4 in it.

Note: This syntax requires just one line. It is easier to type and review for humans.

Java program that uses 2D array initializer public class Program { public static void main(String[] args) { // Use initialize syntax. int[][] values = { { 1, 2 }, { 3, 4 } }; System.out.println(values[0][0]); System.out.println(values[1][0]); System.out.println(values[0][1]); System.out.println(values[1][1]); } } Output 1 3 2 4
Jagged array. This is like a 2D array but with irregular subarray lengths. Its lengths are not even—they are jagged. Here we create a jagged array of two String arrays.ArrayString Arrays

And: The first subarray has two elements. The second one has three String elements. We loop over all these values.

Strings
Java program that uses jagged array public class Program { public static void main(String[] args) { // Create an array of String arrays: a jagged array. String[][] values = new String[2][]; // Fill first row with 2-element array. values[0] = new String[2]; values[0][0] = "cat"; values[0][1] = "dog"; // Use 3-element array for second row. values[1] = new String[3]; values[1][0] = "fish"; values[1][1] = "bird"; values[1][2] = "lizard"; // Display rows and elements. for (String[] array : values) { for (String element : array) { System.out.print(element); System.out.print(" "); } System.out.println(); } } } Output cat dog fish bird lizard
3D array. Usually two dimensions is enough, but we can use three dimensions in an array. And even more are supported. It is rare to need a 3D array.

Tip: Three-dimensional arrays can often be replaced with lesser-dimensioned arrays. This would likely be faster.

Java program that creates 3D array public class Program { public static void main(String[] args) { // Create space cube with 9 points. byte[][][] space = new byte[3][3][3]; space[0][0][0] = 10; space[1][1][1] = 20; // Middle of the cube. space[2][2][2] = 30; // Display points in our space-cube. System.out.println(space[0][0][0]); System.out.println(space[1][1][1]); System.out.println(space[2][2][2]); } } Output 10 20 30
Flattened 2D arrays. A compiler transforms a 2D array indexing operation into multiplication and addition. So to a compiler, a 2D array is similar to a 1D array with an indexing function.

Here: I develop a flattened 2D array, which uses a multiply and add to locate elements in a 1D array.

Indexes: We add the X coordinate to the Y coordinate multiplied by the number of rows. Two indexes are combined into one.

Java program that uses flattened 2D array public class Program { public static void main(String[] args) { // Create 4 by 4 one-dimension array. // Can access 0, 0 through 3, 3 with multiplication. int[] array = new int[4 * 4]; // Assign locations in the flattened array. array[0 + (1 * 4)] = 10; // 0, 1 array[3 + (3 * 4)] = 100; // 3, 3 array[2 + (2 * 4)] = 1000; // 2, 2 // Read those locations. System.out.println(array[0 + (1 * 4)]); System.out.println(array[3 + (3 * 4)]); System.out.println(array[2 + (2 * 4)]); // Read an empty location. System.out.println(array[3 + (2 * 4)]); // 3, 2 } } Output 10 100 1000 0
Benchmark, flat array. Two-dimensional arrays often come with performance losses. The benchmark sets up two 10 by 10 arrays. It then does a load and a store in the arrays.

Version 1: Here we benchmark a flattened array (a 2D array stored as a 1D array).

Version 2: In this version of the code we use a real 2D array, and use 2 indexes to get an element.

Result: The program shows the performance advantage of 1D arrays over 2D arrays. A flat array is nearly twice as fast.

Java program that benchmarks flat, 2D arrays public class Program { public static void main(String[] args) { int[] flat = new int[10 * 10]; // Flattened 10 x 10 array. flat[0 + (4 * 10)] = 1; int[][] two = new int[10][10]; // 10 x 10 two-dimensional array. two[0][4] = 1; long t1 = System.currentTimeMillis(); // Version 1: read, assign flattened array. for (int i = 0; i < 100000000; i++) { int value = flat[0 + (4 * 10)]; flat[9 + (9 * 10)] = value; } long t2 = System.currentTimeMillis(); // Version 2: read, assign 2D array. for (int i = 0; i < 100000000; i++) { int value = two[0][4]; two[9][9] = value; } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 131 ms, Flattened 1D array, load and store 256 ms, 2D array, load and store
Alternatives. We can use alternative data structures to replace a 2D array. A HashMap can store ArrayLists in its keys: we can look up collections by any index value.HashMapArrayList add, insert
A syntax form. 2D arrays use a convenient syntax form for storing data with 2D spatial relationships. We index a 2D array with a pair of coordinates.
Drawbacks. Performance suffers with 2D arrays—using 1D arrays may prove worthwhile. And often programs can be written in a clearer way with simpler collections.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf