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.
Related
Are there any built-in functions (or fast implementations) in Java to convert a single-dimension array of size [n] to a two-dimensional array of size [n][1]?
For example:
double[] x = new double[]{1, 2, 3};
double[][] x2D = new double[][]{{1}, {2}, {3}};
Arrays.setAll method can be used:
double[] x = {1, 2, 3};
double[][] x2D = new double[x.length][];
Arrays.setAll(x2D, i -> new double[]{x[i]});
If you're looking for a built-in function to convert a single dimension array to a two-dimensional one, sadly there isn't one.
However, as it has been pointed out in the comments, you could use streams to reach a fair compact way to initialize your two-dimensional array from a single-dimension one. Basically, you could define your matrix's dimension from the array's length and then rely on a stream to copy the array's elements within the two-dimensional array.
double[] x = new double[]{1, 2, 3};
double[][] x2D = new double[x.length][1];
IntStream.range(0, x.length).forEach(i -> x2D[i][0] = x[i]);
Or in a more concise writing, you could immediately initialize your two-dimensional array with a stream where each element is mapped to a double[] and then collect each one of them into a further array.
double[] x = new double[]{1, 2, 3};
double[][] mat = Arrays.stream(x).mapToObj(i -> new double[]{i}).toArray(double[][]::new);
For example int new [] {1, 2, 3, 4, 5, 6, 7, 8}, I'd like to take 4 of them randomly then insert them to another array for later use.
Dumb question, but does this also need generators? The elements are already there so I don't see any use for generators here...
Below snippet should do the trick:
private static final Random RANDOM = new Random();
public int[] getRandom4( int[] input ){
final int[] output = new int[4];
for( int i = 0; i < 4; i++ ){
output[i] = input[RANDOM.nextInt(input.length)];
}
return output;
}
Note: I prefer the Random instance to be static, but if you dislike that. Then just move it inside the method
You can but the elements inside ArrayList instead of simple array
and then shuffle the elements usingCollections.shuffle(list)
and then take first three or four elements or whatever you wants.
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.
So i am trying to understand multidimensional arrays a little better. So far, I understand there are 2 way to construct these arrays. One is
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
The first array constructs row 0 with 2 columns ( column 0 and column 1). What i don't understand is why are these numbers chosen. Does it always have to be in numerical order, or do the numbers mean something more? If i were to create a new row would it start with 6? Would it just be better for me to construct it this way?
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
Thanks for your help.
Those numbers are meant to be examples. You need not start your next row with "6" if it's not what your solution demands.
Either manner of construction is acceptable. You'd use the second one if you had to compute the values and didn't know them beforehand.
1, 2, 3, 4, and 5 are just data that got entered in this new array.
The array would look like this:
[
[1, 2]
[3, 4, 5]
]
so [0][0] = 1; [1][0] = 3, [1][2] = 5 etc
Those values are just chosen as example.
First: there is no multi-dimensional arrays in Java. There are only arrays containing arrays. Arrays of arrays if you prefer.
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
constructs an array containing 2 arrays of int. The first array contains the numbers 1 and 2, and the second contains the numbers 3, 4 and 5. These numbers could be anything you want. The line declares and populates the array at the same time.
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
constructs an array of arrays of ints, containing two null elements. Then, the first element of the outer array is initialized with an array of 2 ints, and the second element of the outer array is initialized with an array of 3 ints. All the ints are initialized to their default value: 0.
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].