I am preparing for OCAJP exam, I got a problem with the multi-dimensional arrays in java. After go through a video tutorial on YouTube, I think I got an idea about how it works. It says the following statement creates two double dimensional arrays and one array to hold both arrays. Hence it is a three dimensional array.
int arr[][][] = new int[2][4][3];
So I want to get confirmed, that if I want a five dimensional array, this statement would do it.
int arr[][][] = new int[4][4][3];
Try to visualise it geometrically.
A 1-dimensional array is just a list: new int[2]
A 2-dimensional array is a rectangular grid (or a list of lists): new int[2][3]
A 3-dimensional array is a cuboid (or a list of rectangles, or a list
of lists of lists): new int[2][3][4]
After this it gets harder, but :
a 4D array is a list of cuboids (a list
of lists of lists of lists) new int[2][3][4][5]
a 5D array is a grid of cuboids (a list
of lists of lists of lists of lists): new int[2][3][4][5][6]
int arr[][][] = new int[4][4][3];
Is still a 3 dimensional array.
A 5 dimensional array looks like
int arr[][][][][] = new int[4][4][3][4][3];
int arr[][][][][] = new int[4][4][3][X][X];
x can be any number. this is a 5 dimentional array.
Imagine a cube.
int arr[][][] = new int[2][4][3];
Here you have 2 slices of an array of 4x3.
int arr[][][] = new int[4][4][3];
With this, you have 4 slices of an array of 4x3.
So, it stills a three dimensional array.
However, you can save 4 different two dimensional arrays there.
every time you add a new dimension the number of elements grow exponentially. int[4][4][3] means a 3-dimensions array with 4*4*3=48 elements. to create a 5-dimension array add 2 more square-brackets int[2][2][2][2][2] which is an array with 2^5 elements(2*2*2*2*2)
Related
When I was taught 2d arrays, I was taught that they are arrays of arrays, similar to an array of ArrayLists. But I was thinking about it and it is actually really confusing:
ArrayList[] arrOfList = new ArrayList[5];
arrOfList[0] = new ArrayList<Integer>();
arrOfList[0].add(1);
arrOfList[0].add(2);
arrOfList[0].add(3);
//arrOfList[0] is the first list, with 3 elements
//arrOfList is an array of 5 lists; arrOfList.length = 5
int[][] arrOfArr = new int[3][5];
//arrOfArr[0] is NOT an array with 3 elements
//arrOfArr is NOT an array of 5 arrays; arrOfArr.length = 3
I think what I'm getting at is more clear if I bold the parts that I think would correlate (but don't):
ArrayList[] arrOfList = new ArrayList[5];
int[][] arrOfArr = new int[3][5];
What is a more intuitive way of thinking about declaring 2d arrays, since relating it to an arbitrary type is not right? (as illustrated above)
This may help you visualize it more.
When using square brackets [], first pair is always row, second pair is columns.
In both scenarios, the first dimension (row) saves the memory address of the corresponding Array / ArrayLists.
The second dimension (column) saves the corresponding value stored in that particular row of Array/ArrayList.
What you are taught is correct. An array of arrays is similar to an array of arraylists, with the exception that arraylists have variable length. The implication is that with an array of arraylists, the width (no. of columns) isn't static.
ArrayList[] arrOfList = new ArrayList[5]
This is saying, create an Array of length 5 (5 rows), with the data type being ArrayList (of variable length, thus can be any number of columns).
int[][] arrOfArr = new int[3][5]
This is saying, create an Array of length 3 (3 rows), with the data type being Array with length 5 (5 columns).
The fact that an ArrayList has variable length is likely causing the confusion, but I still stand by the same answer: first pair of [] = row; second pair of [] = column.
int[][] arrOfArr = new int[3][5]
That creates an empty grid of array cells with 3 rows and 5 columns. i.e.
[][][][][]
[][][][][]
[][][][][]
Then to fill those columns you just do arrOfArr[0][2] = 4 which goes down to row 0 and across to column 2. i.e.
[][][4][][]
[][][][][]
[][][][][]
Alternatively, see it as a set of 3 lots of 5 cell arrays
[][][4][][], [][][][][], [][][][][]
int[][] arrOfArr = new int[3][5];
//arrOfArr[3] is the number of rows
//arrOfArr[5] is the number of colums
Im using
ArrayList<ArrayList<String>> Stringdata = new ArrayList<ArrayList<String>>();
to make a 2d array of string
how is it different from using
String Stringdata[][] = new String[10][10];
An ArrayList is a class that implements the interface List.
An array as per declared by:String[] variable is a finite-length data-structure in Java.
The main difference in using a 2D ArrayList instead of a normal array is that the length of an ArrayList is not limited. You may add as many elements to an ArrayList as your RAM allows.
On the other hand, String[][] stringData = new String[10][10]; would limit this matrix to 100 elements (10 rows with 10 elements each). If trying to add an element to index 10 (notice the index only goes from 0 to 9) of a 10x10 matrix, the compiler would throw an error.
In general, if you already know how many spaces you will need in your matrix it is recommended that you use an array. Else, ArrayLists are really good.
I have a few multidimensional arrays of type char[][].
Eg..
char[][] ARRAY_1 = {
{'.','#'},
{'$','#'}
}
char[][] ARRAY_2 = {
{'.','#'},
{'$','#'}
}
And I want to make an array or list of some sort such as
ARRAY = {ARRAY_1,ARRAY_2,...}
so I'll be able to put in ARRAY[1] (or something similar) and have it return the entire char[][] ARRAY_1
I am very new to programming with Java so I'm not sure what the best way to do this is.
Edit: I've just found out I'm not allowed to use ArrayLists.
Direct answer: use ArrayList<char[][]> or char[][][].
Basically, you create an ArrayList that holds your 2 dimensional arrays or a 3 dimensional array of chars.
List<char[][]> array = new ArrayList<>();
or
char[][][] array = char[length][][];
To add the arrays, you just use the following:
array.add(arrayOne); //for an ArrayList
array.add(arrayTwo);
or
array[0] = arrayOne; //for an array
array[1] = arrayTwo;
To get the arrays, you just use the following (where the number is the index):
array.get(0); //for an ArrayList
array.get(1);
or
array[0]; //for an array
array[1];
Check out the ArrayList javadoc for more information.
(edit: variable changed to match naming conventions)
So ... if you are not allowed to use lists ... this is one way to make an array of existing arrays.
char[][][] ARRAY = new char[][][]{ARRAY_1, ARRAY_2};
Insight #1: an N-dimension array in Java is an array of N-1 dimension arrays (assuming N > 1).
Insight #2: arrays are indexed from zero.
How would I call the arrays individually again later on?
You still have the names of the original arrays ... in your example.
Base on insight #1":
char[][] ARRAY_1_AGAIN = ARRAYS[0];
System.out.println(ARRAY_1 == ARRAY_1_AGAIN); // prints true
Since ARRAY_1 is the first subarray of ARRAY (as per the previous example), we need to use ARRAYS[0] (not ARRAYS[0]) to access it.
Try this:
List<char[][]> list = new ArrayList<>();
list.add(ARRAY_1);
list.add(ARRAY_2);
Or
char[][][] ARRAY = new char[length][][];
ARRAY[0] = ARRAY_1;
ARRAY[1] = ARRAY_2;
Or
char[][][] ARRAY = new char[][][]{ARRAY_1, ARRAY_2};
Further reading:
ArrayLists in Java
You are using a Jagged Array...
Also try this
char[][] array = new char[5][];
array[0] = array1;
array[1] = array2;
Regards
When I have a two-dimensional matrix in java, but I only want to work with a certain row of that matrix respectively creating a new array that contains the contents of the matrix in that certain row, how would I accomplish that (with primitives)?
So, for example, we would write:
int[][] matrix = new int[10][10];
Now we have a two-dimensional matrix with 10 rows and 10 columns. Assume that we fill the whole matrix with certain elements, and now, I wish to work only with the first row, meaning to define a new array that contains exactly the elements of the first row of the matrix.
Assuming that row means the horizontal segments of the matrix (as it almost always is):
In a 2 dimensional array in java, the rows are the first index and the columns are the second index.
Basically a two dimensional array is an array of arrays. So
int[][] intArray = new int[10][3];
is actually an array of size 10. Each element in the array is an array in itself of size 3.
Say you have an array of integers
int[][] integerArray; //we have to initialize the array.
then we want to work with the 1st row. We would use:
int[] arr = integerArray[0];
LIMITATIONS
The matrix must be initialized (must have values in cells)
The matrix must have a 1st row
Note: we use integerArray[0] because arrays start at index 0, so the third row would be integerArray[2]
I read Java: The Complete Reference(9th). In Character 5: Control Statements - Iterating Over Multidimensional Arrays section
Write:
The enhanced version of the for also works on multidimensional arrays.
Remember, however, that in Java, multidimensional arrays consist of
arrays of arrays. (For example, a two-dimensional array is an array of
one-dimensional arrays.) This is important when iterating over a
multidimensional array, because each iteration obtains the next array,
not an individual element. Furthermore, the iteration variable in the
for loop must be compatible with the type of array being obtained. For
example, in the case of a two-dimensional array, the iteration
variable must be a reference to a one-dimensional array. In general,
when using the for-each for to iterate over an array of N dimensions,
the objects obtained will be arrays of N–1 dimensions. To understand
the implications of this, consider the following program. It uses
nested for loops to obtain the elements of a two-dimensional array in
row- order, from first to last.
I can't understand why "to iterate over an array of N dimensions,
the objects obtained will be arrays of N–1 dimensions". Is it true?
An array of N dimensions is really an array of (N-1)-dimensional arrays. Therefore, when we iterate over an array of N dimensions, we are iterating over all of its constituent (N-1)-dimensional arrays, as indicated.
For example, consider a 2-dimensional array:
int[][] array = {{1,2,3}, {4,5,6}};
This is really an array of 1-dimensional arrays: {1,2,3} and {4,5,6}.
Consider a tridimensional matrix (mathematically defined).
When you iterate through the rows, you are getting two dimensional matrices, and when you iterate through each of the two dimensional matrices you are getting one dimensional vectors.
// Three dimensions
String[][][] stringArray = new String[3][3][3];
// Iterating over one dimension
// results in two dimensional array
for (String[][] strings : stringArray) {
// Iterating over one dimension
// results in one dimensional array
for (String[] strings2 : strings) {
// Iterating over one dimension
for (String string : strings2) {
}
}
}
Imagine your multi-dimensional array as (x, y, z). When you iterate over first coordinate, you fix x (x = 1, 2, ..., n) and get (y, z) 2d-array.
Then you fix y(y = 1, 2, ..., m) and get (z) 1d-array.
When you iterate over an array you "set" one dimension and leave the others not set. So when you have a N dimension array, when you enter the loop you use a N-1 dimension array (inside the for-each loop).