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?

3

4 Answers

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.

5

No matter how you try to shorten your code, it doesn't change the fact that when the call to getCoord() returns, it simply returns a reference to the array, not a copy of the contents of the array.

Trying to make the code more succinct won't help you with your performance problem.

Just don't initialize dim1 to new int[2]; at the beginning if you want, because it gets replaced right after anyways. But that's small potatoes.

There are two ways you could ensure only one array is created.

int[] dim = myObject.getCoord(); 

Or

int[] coord = new int[2]; myObject.setCoord(coord); public void setCoord(int[] coord) { coord[0] = x; coord[1] = y; } 

When you reassign dim1, it forgets the previous value it stored. It's actually the initial (empty) value of dim1 which is getting garbage collected. You could just as easily have done:

int[] dim1 = new int[0]; 

In order to save memory.

For a one-liner, just do:

int[] dim1 = myObject.getCoord(); 

And then in your method use:

return new int[] { y1, x1 }; 

However, this will consume the exact same amount of memory as my first option.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.