Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return an L-value from a function

Tags:

java

As some of you are aware, C++ allows doing this:

get( array, 5 ) = 5;

with the function get implemented something like:

int& get( int* array, int index ) { return array[index]; }

Is something similar possible in Java? More specifically, I'd like to encapsulate array indexing logic in a function (in a high-performance way).

like image 812
Aleksandr Dubinsky Avatar asked Oct 21 '22 19:10

Aleksandr Dubinsky


2 Answers

There's no such option. Non-objects (literals) are primitive types and you cannot simply connect two variables so that when changing one, second becomes also changed.

All objects are represented by its references which you can use to change some attributes of held object. This means that you can code:

getMyObject().setX(newXVal);

But you cannot write:

getMyObject().getX() = newVal;

Because method getX() (and any method that does not return void) always returns value type (when returning Object it is its address, when returning literal it's just this literal's value).

If you want to write performance-optimized code in Java - first write, then measure, and then eventually tune it (if measurement step says it's slow). JVM has enough optimalizations to make your code as fastest as possible, you don't have to optimize code too early.

like image 109
Maciej Dobrowolski Avatar answered Oct 24 '22 11:10

Maciej Dobrowolski


It not possible. Java doesn't pass method arguments by reference; it passes them by value.

You can use something like this:

public static <T> void setArrayValue(T [] array, int index, T set) {
    ...
}
like image 43
Sergey Morozov Avatar answered Oct 24 '22 11:10

Sergey Morozov