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).
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.
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) {
...
}
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