# 2D array

abalfazl hossein

Ranch Hand

Posts: 635

posted 5 years ago

- 0

In Java, a 2D array is really just an array of arrays. So when you get the length of the outer array, you are simply asking how many inner arrays there are - which is four. If you wanted to find the total amount of values that can be stored in the 2D array you could:

1) If you know each inner array is the same size: Look at the length of values[0], and multiply that by the length of values

2) If you allow that each inner array is independent and can have different sizes, ten you must loop through each index of the outer array, and sum the lengths of the inner arrays

1) If you know each inner array is the same size: Look at the length of values[0], and multiply that by the length of values

2) If you allow that each inner array is independent and can have different sizes, ten you must loop through each index of the outer array, and sum the lengths of the inner arrays

Steve

posted 5 years ago

- 0

Here's a little secret...Java doesn't actually have 2D (or 3D, or 4D...) arrays. It only has 1D arrays. However, an array can contain...arrays!!!

What you have created is a 1d array with four elements, and each of those is holding another array. So your values array really does only have a length of 4.

What you have created is a 1d array with four elements, and each of those is holding another array. So your values array really does only have a length of 4.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Ashish Schottky

Ranch Hand

Posts: 93

posted 5 years ago

- 0

I agree with all the posts above. However if you still unable to visualize why you get length as 4 rather than 12, then follow this example.

Think your array as 4 empty boxes and place them in one line. How add three boxes in each box. This is what the code [4][3] means.

So now the length of your boxes is 4 and not 12.

Think your array as 4 empty boxes and place them in one line. How add three boxes in each box. This is what the code [4][3] means.

So now the length of your boxes is 4 and not 12.

I agree. Here's the link: http://aspose.com/file-tools |