What happens to memory when this code is executed?
int[] dim1 = new int[2];
dim1 = myObject.getCoord();
public int[] getCoord() {
int[] dim2 = new int[] {y1, x1} ;
return dim2;
}
It seems that the space is first allocated for two arrays dim1 and dim2. While dim1 will live, dim2 lives for just two lines and then goes to gc. It seems to cause some performance issues with really large arrays. Yet, code below is a compile time error.
public int[] getCoord() {
return {y1, x1} ;
}
What is the logic behind? What is the correct way to create just one array?
do you mean like this?
int[] dim1 = myObject.getCoord();
public int[] getCoord() {
return new int[] {y1, x1} ;
}
only one array is ever created, by the method call, and only has one reference, dim1.
but ideally you probably don't want a "get" method to be creating new things, as just by looking at the declaration you might not expect that. personally, i'd prefer
int[] dim1 = myObject.createCoord();
public int[] createCoord() {
return new int[] {y1, x1} ;
}
which makes it explicit that the method is "creating" a thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With