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).
Related
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]
Here's the question about memory allocation in Java.
Suppose I have an array of ints A[100] and another array of ints B[10][10]. Do they need the same amount of memory in Java or is it different? If the latter, what's the difference and how does it grow with N?
I'm talking here only about Ns that are power of 2 of a positive number, so we're talking here about square 2D arrays and their possible 1D representation.
Definitively, no.
In C/C++ a 2D-array allocates all memory for the 2D-array in "one chunk".
In Java, a 2D-array is an "array of arrays". One-dimensional arrays are allocated in one chunk, but the one-dimensional arrays may be scattered. Furthermore, the "outer" array (2nd dimension) needs heap memory as well, storing the references to the 1D-arrays.
So if one allocates a 2D-array of dimensions m (outer) and n (inner), Java will create one array of m elements and m arrays ofn elements each. The outer array just stores the references to the m inner arrays.
This page gives a nice explanation and visualization of multidimensional arrays in Java.
This is empirical confirmation of #Turing85's answer, and measurement of the overhead. This program alternately allocates and frees a single array of a million elements or an int[1000][1000], reporting the amount of memory in use at each step. It quickly settles down to:
Neither: 291696
1D: 4291696
Neither: 291696
2D: 4311696
showing an extra 20,000 bytes of memory in use for the 2D case.
Here is the program:
public class Test {
public static void main(String[] args) {
int M=1000;
for(int i=0; i<10; i++){
System.out.println("Neither: "+inUseMem());
int[] oneArray = new int[M*M];
System.out.println("1D: "+inUseMem());
oneArray = null;
System.out.println("Neither: "+inUseMem());
int[][] twoArray = new int[M][M];
System.out.println("2D: "+inUseMem());
twoArray = null;
}
}
private static long inUseMem() {
System.gc();
return Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
}
}
Running this program on the system of interest using the actual array sizes should show the cost of using the 2D array. If the arrays really are around 10,000 elements total, it is probably best to go with whatever makes the code more readable.
When an object is creating by using “new”, memory is allocated on the heap and a reference is returned. This is also true for arrays, since arrays are objects.
Single-dimension Array
int arr[] = new int3;
The int[] arr is just the reference to the array of 3 integer. If you create an array with 10 integer, it is the same – an array is allocated and a reference is returned.
Two-dimensional Array
Actually, we can only have one dimensional arrays in Java. 2D arrays are basically just one dimensional arrays of one dimensional arrays.
int[ ][ ] arr = new int[3][ ];
arr[0] = new int[3];
arr[1] = new int[5];
arr[2] = new int[4];
Multi-dimensional arrays use the name rules.
As you can observe that while managing a 2D array extra 1D array is needed thus in terms of memory the size differ but from users view both have same size.
Images were taken form this site.
Basically, I have a 54 element single dimensional array that I wish to split quickly into a two dimensional array containing 20 very specific subarrays of the original array (and ordered correctly).
consider the integers in the I/O as indices of the original array.
input: {0,1,2,3,4,5,6,7,8,9......53} the array containing 54 elements
output: {{0,9,51}, {1,52}, {2,17, 53}, {3,10}, {5,16}, {6,11,12} ...} the multidimensional array of
subarrays of the input array
I am currently hardcoding the subarrays but it is tedious and slow. Any ideas on how to achieve this?
You could do the following. I assume you initialize your sub-arrays yourself. But the sorting of the sub-arrays should be simple as following.
public static void main(String[] args) {
// Initialize your original array
int[] original = new int[54];
// Create a master array containing 20 sub-arrays
int[][] array = new int[20][];
// sub array
array[0] = new int[3]; // and populate the sub-array values
array[1] = new int[2]; // and populate the sub-array values
// .
// .
// .
// Iterate over the sub arrays and sort the numbers
for (int[] subarray : array) {
Arrays.sort(subarray);
}
// At this point you've achieved what you wanted
}
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)
I am trying to have a 2D Array that is 16 rows by 11 columns where row 0, column 3 is a reference to another array that is a single dimension array. How do i go about doing this? I already have both arrays where the single dimension array is a char array(although i could make it a string array if i wanted) and the 2D array is a string array. The rest of the 2D Array is filled with plain strings for each elements with the exception of row 0, column 3 which i want it to be the single dimension array.
Object[] arrayToReference = ...;
Object[][] arrayWithReference = new Object[] { ..., arrayToReference, ...};
This should work; just reference the array and it should change as the original changes
Here's an example code snippet:
Object[] array = new Object[] { "Test!" };
Object[][] arrayArray = new Object[][] { array };
System.out.println("Before: " + arrayArray[0][0]);
array[0] = "Test2!";
System.out.println("After: " + arrayArray[0][0]);
which has the following output:
Before: Test!
After: Test2!
That just sounds like your approach to the problem is wrong. Maybe you should rethink your data structure. Normally, an array is typed. You can't really decide to insert a different type in one cell.
If you really can't change the data structure, try inserting a single dimension array of strings in each cell with only 1 entry in them, which is the string that goes there normally, except for row 0, column 3, which already is an array.
I'm thinking a bit of an overkill solution, but should work for this with some refining. If it is possible for you.
Can you make two classes that implement the same interface? First one will be the type of the 2D array, and the other one would be class with the 1D array.
Since they implement a common interface, you can make a 2D array with that interface. That kind of 2D array can accept any kind of the two objects on any place in it.