Java 2D Array rows vs cols syntax question - java

I am having a hard time understanding why putting brackets versus leaving them out either calls for the rows or cols in a 2D array. I get the syntax I just don't understand why it works that way? Should I just not worry about it and move on with my life?
double[][] values = {
{1.2, 9.0, 3.2},
{8.2, 8.6, -1.2},
{-7.3, 2.5, 9.7},
{4.1, 7.0, 5.1},
};
System.out.println("Number of Rows: " + values.length);
System.out.println("Number of Cols: " + values[0].length);

a 2D array is an array of arrays. The variable length returns the number of elements in the array.
so values.length gives the number of elements in the outer array which are the inner arrays (rows)
and values[0].length gives the number of elements in the first inner array (columns)

values.length gives you the length of the outer array. That is the array containing 4 rows. The outer array happens to contain objects that are themselves arrays.
values[0].length gives you the length of the 1st (0th) object in the outer array. This 1st object is itself an array. Since your 2D array is rectangular, every row has the same number of elements, or columns. So getting the length of any one of them will give you the number of columns
Hope that's clearer!

Related

2d Array length rows and column length (Java) [duplicate]

This question already has an answer here:
How to get rows and columns count of a 2D array in Java? [duplicate]
(1 answer)
Closed 4 years ago.
int[][] example = {{1,2,3},
{2,3,4},
{6,7,8}};
We can get the length of the column in a 2d array using example[0].length,
but how the length of the row is determine using example.length?
NOTE : I am asking for an explanation for Why example.length is used to get the length of row? not how to get the length of columns and row in 2d array? .
Think of it like this: for a 2-D array such as int[][] example, the number of rows is example.length, while the number of columns in a row, eg. example[0], is the length of that particular row, which can be expressed as example[0].length.
Note: the number of columns in each row can be different. For example, you could define example as:
int[][] example = { {1, 2}, // row of length 2
{2, 3, 4}, // row of length 3
{6} }; // row of length 1
Java technically doesn't have 2-dimensional arrays, it has arrays of arrays.
System.out.println(example.length); // number of rows
System.out.println(example[0].length); // number of columns in first row
But This could fail if:
array size is 0, in which you will get an exception.
You are explicitly assuming that size of first element of array as size of rows, this could be ambiguous if you are taking a Jagged array.
Jagged Array: Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row.

Why can I not get a one dimensional array of a column as easy as a row?

Background
This is a 2d array.-
String[][] names = { {"Sam", "Smith"}, {"Robert", "Delgro"}, {"James", "Gosling"}, };
I can access the rows by calling this:
names[n]
Where n is any integer between the bounds and in this case 0<=n<=names.length-1.
Likewise
I can call this
String [] rowOne = names[0];
Inquiry
The question now remains,instead of rows, is there a way to access a specific column in the same way a specific row is accessed.
Feedback
I would like feedback on this suggestion.
In the particular case of accessing a column in a 2d array,names[][x]would be the declaration to call a specific column,where 0<=x<=names[0].length-1.
String[] columnOne = names[][0]
This would mean that names.length would be equivalent to calling names[][x].length
This could also work for arrays greater than a 2d array.
String[][][]names = { {{"Sam", "Smith"}, {"Robert", "Delgro"}}, {{"James", "Gosling"}}};
Just add extra square brackets.
For example In a 3d array, to access an aisle, which is what I will refer to the 3rd dimension.
names[][][z], where 0<=z<= names[0][1].length-1
One dimensional arrays from multi-dimensional arrays.
...is there a way to access a specific column in the same way a specific row is accessed.
No; Java's multidimensional arrays are essentially arrays that contain references to other arrays are not contiguous in memory. Java also allows arrays to be jagged. Let's say you have the following multidimensional array:
int[][] array = {
{1, 2, 3},
{4, 5},
{6}
};
By calling array[][2], what would you expect to receive? What about array[][3]?
To be able to get an array of columns, you would need to first transpose the multidimensional array.

2D array row and column length

I'm studying 2D array right now, there is a part of 2D array I don't really understand. I will show my code and explain what part I don't understand.
My code:
public static void main(String[] args){
int[][]array={{1,2,3},{1,2,3},{1,2,3}};
}
public static printArray(int[][]a){
for(int row=0;row<a.length;row++){
for(int column=0;column<a[row].length;column++)
}
My question is for the second method of printArray. In the second for loop,what does column<a[row].lengthmeans?
This line gives the size of each row.
You know that
a[0]={1, 2, 3}
a[1]={1, 2, 3}
a[2]={1, 2, 3}
So, a[0].length = a[1].length = a[2].length = 3. Use of this is to ensure that we dont go Out Of Array Bounds.
Java doesn't have 2D arrays. Java has arrays of arrays. The second loop uses column < a[row].length to make sure that you don't iterate past the length of the row-th array. You need this to handle nested arrays of varying length.
That is the condition to check when the limit of each row is reached, in order to avoid an ArrayIndexOutOfBoundsException
A 2D array means that each element of the array is itself an array. The second loop allows you to loop through each {1,2,3} array (in your case). But to do that, you need the length of each array. That's what a[row].length provides.

Creating a new 2D array that = size of 2D array 1 + size of 2d array 2 (rows and columns)

public static int[][] add2DArrays(int[][]A, int[][]B) {
return int[][] C;
}
I understand how to populate this new array by adding the sums of the two arrays A & B, the road block I am facing is creating this initial array C. We cannot assume the size of the arrays given as parameters, so that is the part I am having a problem with.
I know by doing:
int[][] C = new int[A.length+B.length][]; //this will only give me the # of rows;
I am stuck on how to get the proper length of columns for the rows in the new array. I am thinking it may be possible to some how record the length of the longest row in A, and then record the longest row in B, and choose the bigger of the two, but that seems messy and inefficient. Thank you all for your support.
If both are really 2D arrays -- that is, the length of all the rows is the same -- and row 0 was actually allocated, you can get the summed length of a row from A[0].length+B[0].length
If the length of the rows might vary -- which is perfectly legal in Java -- then you might need to iterate through A and B to find the longest row and use that length.

Why is this an array out of bounds exception?

Why does this cause an array out of bounds exception ?
x[10][2] = 5;
Should this be assigning the 3rd spot of the 11th array, the value 5
I thought of it in a rectangular way.
Its like we have to count 11 rows(representing the 10 arrays)
and then we have to go to the 3rd column that is the 2
OR
I should be looking at it as an array looking for the 11th spot in an array of size 2 that doesn't actually exist ?
Is the 11th element of x an array? If it is, what is its length?
You are receiving that error because it's likely the length of that element is less than 3.
Test it by trying
System.out.printf(x[10].length);
Hope that helps.
Why does this cause an array out of bounds exception?
x[10][2] = 5;
This only happens when you try to access a position out of the range that you had defined for your array. For example
int x[20][20];
You can make x[10][2] = 5; without a problem because 10 < 20 and 2 < 20. But if you did:
x[30][20] = 5;
You would have the out of bounds exception because you are trying to access the position (30,20) of the 2D array, a position that surpasses the size of the 2D array.
It is because x[10][2] does not exist.
It can be either because x[10] is not a valid element (i.e. x.length is equal to or greater than 10), or x[10][2] is not a valid element (i.e. x[10].length is equal to or greater than 2). The exception message tells you which index fails, if they differ.
Note that a multidimensional array doesn't have to be a matrix. This is called a jagged array.
For example, consider the following code (from Wikipedia):
int[][] arr = new int[2][]; // creates 2 rows
arr[0] = new int[3]; // 3 columns for row 0
arr[1] = new int[5]; // create 5 columns for row 1
Referencing arr[0][4] would throw an ArrayIndexOutOfBoundsException, while referencing arr[1][4] would not.
As Mark Stevens already mentioned in the comments, which one is the row and which one the column, is subjective. As opposed to what jazzbassrob says in the comments, Java has neither row-major nor column-major order. In fact, in Java, there is no such thing as a two-dimensional array, instead, it's actually an array of arrays.

Categories