Consider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
Answer from NG. on Stack OverflowConsider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
int[][] test;
test = new int[5][];//'2D array'
for (int i=0;i<test.length;i++)
test[i] = new int[i];
System.out.println(Arrays.deepToString(test));
Object[] test2;
test2 = new Object[5];//array of objects
for (int i=0;i<test2.length;i++)
test2[i] = new int[i];//array is a object too
System.out.println(Arrays.deepToString(test2));
}
}
Outputs
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
The arrays test and test2 are (more or less) the same.
Array length question
Java is it possible to change 2D array length?
Two-Dimensional Arrays: Why is the length of a two-dimensional array the number of rows of the array?
How do I find the number of rows and columns of a 2D array?
Videos
I've been playing around with arrays lately, and i found a piece of code that i haven't figured, spoiler alert this might be a dumb/basic question but when run this code:
public static void main(String[] args) {
char grid[][]={{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}};
System.out.println(grid[0].length); //prints 4, WHY?}
My question is why is grid[0].length = 4?
Is it excluding the 0 position out of the array and considering 1 though 4?
I don't know what's going on to make it print that value.
So as we know 2D arrays have to indices. I want to change the second index. So the first indices point to knew indices. For example: a points to 1, 2,3. But i want to change it to 4,5,6.