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);
Related
I am studying for an exam and this is about memory allocation of a multidimensional java array.
Given is the following code:
double [][] a = new double[4][];
for (int i = 0; i < 4; i++)
a[i] = new double[4-i];
I am supposed to draw the memory layout of this array, but I am afraid I don't fully comprehend how it even works.
It would also be very kind of you if you could show me how to print this array as list to the console so I can look at it. :)
Thank you for your time.
you don't have to create new array in the for loop. Try this:
double[][] a = new double[4][3];
Or you can initialize it in one statement like:
double[][] a = {
{1, 3, 2},
{4, 5, 6},
{7, 8, 9}
};
And then print:
System.out.println(Arrays.deepToString(a))
Since your array a is an array of array (2D) , you can use enhanced for loop to print elements.
So, your outer loop has double[] as type, and hence that declaration. If you iterate through your a in one more inner loop, you will get the type double.
double[][] a = {
{1, 3},
{4, 5},
{7, 8}
};
List<Double> dou = new ArrayList<Double>();
for (double[] k: a) {
for (double element: k) {
dou.add(element) ;
}
}
System.out.println(dou);
Output
[1.0, 3.0, 4.0, 5.0, 7.0, 8.0]
I am not sure if this answers your question.
Above picture depicts how array elements will be stored in memory.
I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
Check out the Arrays.fill methods.
int[] array = new int[4];
Arrays.fill(array, 1); // [1, 1, 1, 1]
You can also do it as part of the declaration:
int[] a = new int[] {0, 0, 0, 0};
Arrays.fill(). The method is overloaded for different data types, and there is even a variation that fills only a specified range of indices.
In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:
int[] data = IntStream.generate(() -> value).limit(size).toArray();
Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.
Demo.
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
An array can be initialized by using the new Object {} syntax.
For example, an array of String can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
Check out the Arrays.fill methods.
int[] array = new int[4];
Arrays.fill(array, 1); // [1, 1, 1, 1]
You can also do it as part of the declaration:
int[] a = new int[] {0, 0, 0, 0};
Arrays.fill(). The method is overloaded for different data types, and there is even a variation that fills only a specified range of indices.
In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:
int[] data = IntStream.generate(() -> value).limit(size).toArray();
Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.
Demo.
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
An array can be initialized by using the new Object {} syntax.
For example, an array of String can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
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].