Say I have a 2D array:
int[][] foo = new int[3][10];
I want to have a better alias name for each 1D array, like:
int[] xAxis = foo[0];
int[] yAxis = foo[1];
int[] zAxis = foo[2];
Is xAxis a reference to the 1st 1D array in 2D array? Cause I don't want the array to be copied again. If not, how do I get the reference to 1D arrays.
http://www.functionx.com/java/Lesson22.htm
...with one-dimensional arrays, when passing an multi-dimensional
array as argument, the array is treated as a reference. This makes it
possible for the method to modify the array and return it changed
when you declare this
new int[3][10]
you got one object array with 3 values: array1, array2, array3. All arrays will share the same defined size (10)
so, yes! in this case, foo[0] -> array1[10] , foo[1] -> array2[10] and foo[2] -> array3[10]
consider this one: what did you expect if foo[0] didn't pointing to another array? how (foo[x])[y] should works?
Yes it is reference to 1st Array in 2nd Array. You can verify it by yourself by modifing the xAxis array and check if reflects in 1st 1D array of 2D array.
Short answer - yes. The statement int[] xAxis = foo[0]; assigns the 1D array in foo[0] to the variable xAxis. Since arrays in Java are objects, this just assigns a reference. The data isn't being copied again.
Yes, array's are not primitive types, instead they are reference types.
So in your case xAxis will be a reference to foo[0]. Which means changes will be visible in both foo[0] and xAxis.
But you need to change your first statement to,
int[][] foo = new int[3][10];
I just tried out this code.
int[][] foo = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[] xAxis = foo[0];
int[] yAxis = foo[1];
int[] zAxis = foo[2];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
foo[i][j]++;
}
}
for(int i=0;i<3;i++){
System.out.println("X: " + xAxis[i] + " Y: " + yAxis[i] + " Z: " + zAxis[i]);
}
And yes, it indeed does reference it.
Related
An array in Java is an object. So if I have a 2D array double[][] matrix = new double[5][5] then each row of that array is an object referencing a single dimensional array in memory. From my understanding, once the array size is set in java it can not be changed. So let me declare a 1D array double[] d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} I am then allowed to set matrix[1] = d so that row 1 is now pointing to d in memory. I seems like the array size is not really fixed. I can declare matrix to be of any size and just change the reference to point to an array of a different size. Why am I allowed to do this if the matrix size is fixed to be 5 x 5 ?
The assignment
double[][] matrix = new double[5][5];
actually creates 6 array objects. One array whose element type is double[] (i.e. an array of double arrays) having a length of 5 and referenced by the matrix variable, and 5 arrays whose element types are double having a length of 5 and references by matrix[0]...matrix[4].
Just as you can change the matrix variable to refer to a new array by assigning :
matrix = new double[10][10];
you can also change any of the references matrix[i] to refer to a new array by assigning :
matrix[i] = new double[6];
You are not changing any existing array. You are changing the value of a reference variable which referred to one array to refer to a different array.
Simply spoken: because that is how the fathers of Java made arrays work.
And the syntax gives a hint there:
double[][] matrix = new double[5][5]
You see, the 5,5 only shows up on the right hand side! Meaning: the array dimensions are not part of "type" of matrix!
The key thing is: there are no true "multi dimensional" arrays in Java. There is no way to say: this thing should be "5 x 5". You always end up with an array of "rows"; and each row contains an array of columns. And therefore, those columns can have different lengths,as they are completely independent of each other!
Which one is valid statement?
int[] x =new int[0]{};
new int[2];
int[] x=new int[][]{{1}}[0];
int[][] x = new int[]{0}[0][0];
int x= new int[2]{}[];
The correct answer is 3, and I can understand why it's not 1, 2 or 5, but I don't understand 3 or 4 mean.
1) int[] x =new int[0]{};
You cannot specify both a length 0 and an array initializer at the same time.
2) new int[2];
It's not a statement. It would become a statement if it were assigned to something else, among other possibilities.
3) int[] x=new int[][]{{1}}[0];
This declares and initializes a 1x1 2D array, with 1 being its only element. Then, array access is used to immediately access the "row" at position 0, the only such "row", which is itself a 1-length 1D array, and that is assigned to a 1D array.
4) int[][] x = new int[]{0}[0][0];
There is a lot wrong here. A 1-length, 1D array is created, but there are two array accesses on it. You can only supply one, because it's a 1D array.
5) int x= new int[2]{}[];
The extra [] doesn't do anything and is invalid syntax. Even if they're removed, you can't assign an int array to a scalar int. Also you can't specify a length and an array initializer {} at the same time.
When you declare and initialize an array using {} you are not allowed to indicate the number of items in the array ergo int[0] should be int[]. So it should have been int[] x = new int[]{}.
This is an initialization without a declaration so it should have been something like int[] x = new int[2].
This is correct because it assigns a declaration to an item of two-dimensional array which is an array itself. So the array returned from new int[][]{{1}}[0] is new int[]{1} and thus int[] x = new int[]{1}.
This is totally wrong and messed up. new int[]{0}[0][0] is trying to get a value of a two-dimensional array from a one-dimensional array and assign that to a the array x.
Here as discussed already in point 1, plus trying to access an array with an empty index [] which not possible.
Why we cannot use array intializer after declaring an variable.
For example:
int arr[];
arr = {1,2,3,4};
But,
int arr[] = {1,2,3,4};
is correct.
Is there any way to use array initialize after declaring an variable.
This is how you can.
int arr[];
arr = new int[]{1, 2, 3, 4};
There are three steps to creating an array, declaring it, allocating it and initializing it.
Declaring Arrays
Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance.
Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:
int[] k;
float[] yt;
String[] names;
In other words you declare an array like you'd declare any other variable except you append brackets to the end of the variable type.
Allocating Arrays
Declaring an array merely says what it is. It does not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above:
k = new int[3];
yt = new float[7];
names = new String[50];
The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. Therefore this step is sometimes called dimensioning the array. More commonly this is called allocating the array since this step actually sets aside the memory in RAM that the array requires.
This is also our first look at the new operator. new is a reserved word in java that is used to allocate not just an array, but also all kinds of objects. Java arrays are full-fledged objects with all that implies. For now the main thing it implies is that we have to allocate them with new.
Initializing Arrays
Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException.
You can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.
Here's how we'd store values in the arrays we've been working with:
k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";
We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:
int[] k = {1, 2, 3};
float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};
see http://www.cafeaulait.org/javatutorial.html#xtocid499429
Because an array doesn't work like that in java.
int arr[4];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
Check this
example :-
int data[] = new int[] {10,20,30,40,50,60,71,80,90,91 };
or
int data[];
data=new int[] {10,20,30,40,50,60,71,80,90,91 };
If I declare a 2d array, for example:
int[][] numbers = new int[5][];
I thought that you had to individually declare/initialize each of the 5 int[]?
For example, before I assign a value to numbers[0][1], I would have to say:
numbers[0] = new int[4];
I wrote a small program and explicitly put a value in numbers[0][1], ran it, and it worked without initializing numbers[0] first.
Am I completely off thinking that the individual arrays have to be initialized first in a 2d array?
Edit: My misunderstanding was in the initialization. The 1st 2 statements are ok, because I declared the length of each int[] in goodArray to be 3, which causes all of them to be initialized. Whereas in the badArray declaration, I only declared how many arrays there were(3), so I get a npe:
int [][]goodArray = new int[3][3];
goodArray[0][1] = 2;
int[][] badArray = new int[3][];
badArray[0][0] = 2;
With multidimensional arrays in Java, you can specify a position, there is no need to individually define them.
You can easily test the behavior of the 2D arrays using examples like the one below:
int[][] numbers1 = new int[][] { {1, 2, 3}, {1, 2, 3, 4, 5}}; /* full initialization */
numbers1 = new int[3][]; /* [3][0] is null by default */
try {
System.out.println(numbers1[0][0]);
} catch (NullPointerException e) {
System.out.println(e);
}
numbers1[0] = new int[3]; /* all three ints are initialized to zero by default */
System.out.println(numbers1[0][0]);
numbers1[0] = new int[] {1, 2, 3};
System.out.println(numbers1[0][0]);
Will produce the following output:
java.lang.NullPointerException
0
1
int[][] numbers = new int[5][];
With the previous line you have created 5 int[] one dimensional array. Now you need to say the size for each one dimension array before you use them. Java gives this flexibility ao that you can have variable size one dimensional int [] arrays inside 2D array.
Integer[] ints = list.toArray(new Integer[]{});
If I remove "{}" the compiler asks to fill in a dimension for the array. What do the two braces mean as a command?
It means you initialize the array with what is in between the braces. Ex:
new Integer[] { 1, 2, 3}
Makes an array with 1, 2 and 3. On the other hand:
new Integer[] {}
Just mean that you initialize an array without any values. So it is the same as new Integer[0].
This actually means empty array. The {} allow you to supply the elements of the array:
Integer[] ints = list.toArray(new Integer[]{1, 2, 3});
is equivalent to:
Integer[] ints = new Integer[3];
ints[0] = 1;
ints[1] = 2;
ints[2] = 3;
Check this link:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
for more information - go to Creating, Initializing, and Accessing an Array section.
Yes, an empty array. Just like Integer[0].