• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Width  RSS feed

 
Rick Lohmeyer
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain to me why there is no method or variable to get the width of an Array? One can easily get Array.length, but there is no Array.width. Why?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Java arrays really have only one dimension. If you declare a 2-dimensional array, what you really get is an array of arrays; a 3-d array is an array of arrays of arrays. As such, there's no unique answer for the "width" because every element of the "backbone" of a two-dimensional array could legally hold a different-sized one-dimensional array; i.e., this is an int[4][]. The "backbone" has four elements, but each of those elements has a different length (represented by a different number of X's.) As this is perfectly legal, the question "what is the 'width' of this array" is meaningless.

[0] -> XXXXXXXX
[1] -> XXXXX
[2] -> XXXXXXXXXXX
[3] -> XXX

Now, if you know you have a square array "int[][] m", then the width is

m[0].length

i.e., the length of the first item in the backbone array.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!