This is my first question in a community like this, so my format in question may not be very good sorry for that in the first place.
Now that my problem is I want to deep copy a 2 dimension array in Java. It is pretty easy when doin it in 1 dimension or even 2 dimension array with fixed size of rows and columns. My main problem is I cannot make an initialization for the second array I try to copy such as:
int[][] copyArray = new int[row][column]
Because the row size is not fixed and changes in each row index such as I try to copy this array:
int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};
So you see, if I say new int[3][4] there will be extra spaces which I don't want. Is there a method to deep copy such kind of 2 dimensional array?
I think what you mean is that the column size isn't fixed. Anyway a simple straightforward way would be:
public int[][] copy(int[][] input) {
int[][] target = new int[input.length][];
for (int i=0; i <input.length; i++) {
target[i] = Arrays.copyOf(input[i], input[i].length);
}
return target;
}
You don't have to initialize both dimensions at the same time:
int[][] test = new int[100][];
test[0] = new int[50];
Does it help ?
Java 8 lambdas make this easy:
int[][] copy = Arrays.stream(envoriment).map(x -> x.clone()).toArray(int[][]::new);
You can also write .map(int[]::clone) after JDK-8056051 is fixed, if you think that's clearer.
You might need something like this:
public class Example {
public static void main(String[] args) {
int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};
int[][] copyArray = new int[envoriment.length][];
System.arraycopy(envoriment, 0, copyArray, 0, envoriment.length);
}
}
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'm doing some Java code challenges and am trying to write the entire class w/ a constructor and main() instead of a regular method just to get some extra practice in. I've tried running it in Eclipse and JGrasp and got the same output: [I#6d06d69c
Does anyone have a clue as to what I'm doing wrong? Thanks in advance for your help :)
/*
Given an int array, return a new array with double the
length where its last element is the same as the original
array, and all the other elements are 0. The original
array will be length 1 or more. Note: by default, a
new int array contains all 0's.
makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}
*/
public class MakeLast {
public MakeLast(int[]nums){
int[] result = new int[nums.length *2];
result[result.length-1] = nums[nums.length-1];
System.out.println(result);
}
public static void main(String[] args) {
int[] nums = {3, 5, 35, 23};
new MakeLast(nums);
}
}
result is an array, you cannot print it directly using System.out.println. Instead try the below.
System.out.println(Arrays.toString(result));
If you want more controlled output of the elements in the array, you can iterate through the elements in the array and print them one by one. Also you can check the javadoc for toString method in Object class to see what [I#6d06d69c means.
You can not print the array directly by System.out.println() method in java.
For that you have to use the toString() method present in Array class of util package. Moreover here you can directly use result[7] to see the value.
import java.util.*;
class MakeLast {
public MakeLast(int[]nums){
int[] result = new int[nums.length *2];
result[result.length-1] = nums[nums.length-1];
System.out.println(result.length);
System.out.println(result[7]);
System.out.println(Arrays.toString(result));
}
public static void main(String[] args) {
int[] nums = {3, 5, 35, 23};
new MakeLast(nums);
}
}
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.