Dog[] d = new Dog[3]
int[][] a = new int[][3]
int[][] a = new int[3][]
Mohamed Sanaulla | My Blog | Author of Java 9 Cookbook | Java 11 Cookbook
Campbell Ritchie wrote: int[][] numbers = new int[3][]; means I want numbers to be an array holding three int[] arrays, which do not yet exist.
Guy Hayward wrote:To declare and create an array that could take 3 Dogs:
Dog[] d = new Dog[3]
although no dogs exist yet.
Following that same pattern, to create an array that
could hold 3 int[] objects, I would expect
int[][] a = new int[][3]
where I'm saying that I want to create an array on the heap,
with 3 elements, each element being a reference to an int[] that
doesn't exist yet.
But this won't compile. The rules for creating multidimensional arrays
where only one dimension is specified require
int[][] a = new int[3][]
Is the rule for denoting an array of x ,
where brackets are added immediately to the right of x ie x[]
not consistent throughout java?
Guy Hayward wrote:
Campbell Ritchie wrote: int[][] numbers = new int[3][]; means I want numbers to be an array holding three int[] arrays, which do not yet exist.
Yes. So the syntax seems inconsistent.
If I want an array holding 3 Dog objects that don't yet exist, I use
new Dog[3]
the [3] comes after the Dog datatype.
If I want an array holding 3 int[] objects that don't yet exist, I have to use
new int[3][]
where the [3] is inserted in the middle.
Regards
Richard
Jayesh A Lalwani wrote:
Right? Right?
I think what you are saying makes sense for the point of view of language design.
To answer your question, the reason why they did this is because most programming languages do it like this and all of them do it this way to be compatible with mathematical array notations
Generally in Matrix algebra, A(i,j) denotes the the ith row and jth column of matrix A. Java models this as A[i][j]
They could have done it so you have to denote A(i,j) as A [j][i], but you will end up confusing a lot of mathematicians, and early programmers were all mathematicians . They just stuck with the notation that they were comfortable with
In short, it is this way because it made sense to people who created programming languages
Slideshow boring ... losing consciousness ... just gonna take a quick nap on this tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|