[Solved] Array of arrays “newing” syntax is backwards?

Introduction

Array of arrays, or “nested arrays,” is a powerful concept in programming that allows for the storage of multiple sets of data in a single array. This concept can be used to store complex data structures, such as a list of lists, or a matrix. However, when using the “newing” syntax to create an array of arrays, the syntax can be confusing and backwards. This article will explain the syntax and provide examples of how to use it correctly. Additionally, it will discuss the advantages and disadvantages of using this syntax.

Solution

No, the “newing” syntax is not backwards. The syntax is used to create a new array of arrays, which is done by using the “new” keyword followed by the type of array (in this case, an array of arrays) and then the size of the array. For example, to create a new array of arrays with three elements, the syntax would be:

int[][] myArray = new int[3][];


Array of arrays
As this blog post explains, they wanted to keep the order of brackets the same when creating an array and when accessing elements of the array. I’ll try to summarize.
When you access an array like this:

array[1][2]

that means: take the array at index 1 and get the element of that array at index 2.
So, when creating the array, you have to initialize it like so:

new int[5][]

which means an object that holds 5 int arrays.
Weirdness cannot be avoided. Either the order of the brackets is weird when creating the array or the order is weird when accessing the array. The weirdest option would be when the order is different both times.

2

The concept of “newing” syntax can be confusing for some, especially when it comes to array of arrays. The syntax for creating an array of arrays is actually the opposite of what one might expect. Instead of “newing” the array, the syntax requires that the array be declared first, and then the individual elements of the array can be added.

For example, if one wanted to create an array of arrays, they would first declare the array like so:

int[][] myArray = new int[3][3];

This declares an array of 3 elements, each of which is an array of 3 elements. Then, the individual elements of the array can be added like so:

myArray[0][0] = 1;
myArray[0][1] = 2;
myArray[0][2] = 3;
myArray[1][0] = 4;
myArray[1][1] = 5;
myArray[1][2] = 6;
myArray[2][0] = 7;
myArray[2][1] = 8;
myArray[2][2] = 9;

This syntax is the opposite of what one might expect when it comes to “newing” an array of arrays. Instead of “newing” the array, the syntax requires that the array be declared first, and then the individual elements of the array can be added.