To create an length 5 int array, we use the syntax:
int[] x = new int[5]
To create a 2 dimensional array, an array of int arrays, we say:
int[][] x = new int[5][];
This creates an array of length 5, which can hold int[] objects.
For this second case, why isn't the syntax this: ?
int[][] x = new int[][5]
After all, 5 defines how many int arrays we can have. Not the size of the int arrays that we're going to put into x.
It would be really weird to have the indices for lookups be different from the indices for construction. So if you had int[][] x= new int[][5], then you'd look up the elements with x[0..4][foo], which is just more confusing than the alternative.
The array bring declared is the first dimension, so declaring the referenced array size does nothing to allocate the actual array. It would be similar to coding this:
int[] a = new int[];
Related
Well, that might be a strange question, and maybe just because I'm not familiar enough with Java.
So, I declared a 2D int array:
int[][] arr = new int[0][10]
Now, as you can see, the second dimension's length is 10, while the first dimension's length is 0. I'm not sure how Java treats these kind of arrays, but the compiler doesn't produce any errors, which means it's a legit declaration.
Well, I passed the array to some function, and I want to retrieve from within the function, the length of the second dimension.
Of course something like:
arr[0].length
won't work. is there another way to do this?
The objects created by new int[0][10] and new int[0][20] are equivalent. There is no logical "second dimension" here. Effectively you're running something like this:
int[][] createArray(int d1, int d2) {
int[][] ret = new int[d1][];
for (int i = 0; i < d1; i++) {
ret[i] = new int[d2];
}
return ret;
}
Now if you translate that into your scenario, you'll end up with code which never reads d2.
If you want to represent a general-purpose rectangular array (instead of an array of arrays) you might want to consider creating your own type for it.
Arrays in Java, and most every other programming language, are zero-based. Consider this 2D array:
int[][] arr = new int[1][10];
This means that there is one row and ten columns in it.
Now, consider this array:
int[][] arr = new int[0][10];
This means that there are zero rows and (an irrelevant amount of columns) in it.
If you try to index into the second array, you'll find that you can't - an array of length zero has no starting point.
The compiler sees it as valid because you declared dimensions with it, but you won't be able to actually use it in any meaningful way in Java.
There is no such thing as the length of the second dimension. Consider:
int[][] arr = new int[10][10];
arr[5] = new int[42];
What is the length of the second dimension? 10 or 42?
No. It doesnt work this way. arr is an array with ten elements, each of which must be a reference of an int array (or null). That's all there is to say.
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
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 };
I know that I can add a dimension to an array by adding another [] beside it. But can I have more than one Dimension in a java.util.ArrayList? How might I accomplish this?
List<ArrayList<Integer>> twoDArrayList = new ArrayList<ArrayList<Integer>>();
#rgettman's answer gets the job done, however there are a few caveats to take note of:
Caveat 1: dimensions
In the most common use case the dimensions of the array are pre-defined, for instance:
int[][] array = new int[5][6];
In that case, the array will be of a "rectangular" form of the dimensions defined:
0 1 2 3 4 5
0 [][][][][][]
1 [][][][][][]
2 [][][][][][]
3 [][][][][][]
4 [][][][][][]
As suggested by another member in the comments below, there's more to it. A "two-dimensional array" is merely an array of other arrays, and the line of code above is short-hand for:
int[][] array = new int[5][];
array[0] = new int[6];
array[1] = new int[6];
array[2] = new int[6];
array[3] = new int[6];
array[4] = new int[6];
Alternatively, the child arrays could be instantiated with different sizes, in which case the "data shape" would no longer be rectangular:
int[][] array = new int[5][];
array[0] = new int[2];
array[1] = new int[4];
array[2] = new int[1];
array[3] = new int[6];
array[4] = new int[3];
0 1 2 3 4 5
0 [][]
1 [][][][]
2 []
3 [][][][][][]
4 [][][]
Using the ArrayList<ArrayList<Integer>> approach will result in a "list of lists" where the length of all lists involved will grow as a result of the operations performed.
There is no shorthand to pre-define the dimensions. The child lists must be inserted into the master list, and data elements must be then inserted into the child lists. The shape of the data would thus resemble the second example:
0 [][] <- list with 2 elements
1 [][][][] <- list with 4 elements
2 [] ...and so on
3 [][][][][][]
4 [][][]
Caveat 2: default values of data
Arrays allow the use of primitive data types (such as "int"), as well as their boxed counterparts (such as "Integer"). These behave differently, when it comes to default values of elements.
int[][] array1 = new int[5][6]; // all elements will default to 0
Integer[][] array2 = new Integer[5][6]; // all elements will default to null
Lists (like all other collections) only allow the use of boxed types. And therefore, while it's possible to pre-define the length of a list, the default value of its elements will always be null.
List<Integer> = new ArrayList<Integer>(10); // all elements will default to null
Yes, it's possible. Just have the elements of your ArrayList also be ArrayLists.
ArrayList<ArrayList<Integer>> twoDArrayList = new ArrayList<ArrayList<Integer>>();
This would work with not just ArrayLists, but other collection types as well.
Yes, you can! In a regular array, when you add the second pair of braces, you are creating a normal array that stores Objects of type array. You can just do the same thing here, making the ArrayList hold things of type ArrayList: ArrayList<ArrayList<Object>> list = new ArrayList<ArrayList<Object>>();