Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an array in one line in Java?

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?

like image 734
Steve Avatar asked Oct 28 '25 06:10

Steve


1 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.

like image 142
John Gardner Avatar answered Oct 30 '25 19:10

John Gardner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!