Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Array simple question  RSS feed

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




Are these equal?

This returns 3:




How can I know the length of 2D array by using length?

 
Mohamed Sanaulla
Bartender
Posts: 3179
34
Google App Engine Java Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first case- Its an Array of Arrays- So the length of the Array is still 3, but each element can have an array of any size. That means


But in the second case- Its just an array of int whose size is 3. In both the case- the size of the array is 3, but the contents differ.If you want to find the size of the multidimensional array you can find the size of the each individual array and sum it up.
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The length of an array is the numbers of elements, Right? The number of elements that are hold in that array is more than 3.
 
Mohamed Sanaulla
Bartender
Posts: 3179
34
Google App Engine Java Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
abalfazl hossein wrote:The length of an array is the numbers of elements, Right? The number of elements that are hold in that array is more than 3.


The number of elements in the Array(parent array) is just 3- But each element(child array) can in turn contain many other elements, but that doesn't contribute to the length of the parent array
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always think of eggs when I think of multi-dimensional arrays. You can have an egg.

a 1-d array is an egg carton - it can hold some eggs.

a 2-d array is a crate that holds egg cartons.

a 3-d array is a shipping palate full of crates.

a 4-d array is a tractor-trailer full of palates...

etc...

so "int[][] s = new int[3][];" creates a crate that can hold 3 egg cartons - but you don't know how many eggs each carton can old...and in fact, each carton can potentially hold a different number of eggs.

whereas "int[] s = new int[3];" creates a single egg carton that can hold exactly three eggs.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!