Use vec_x.set(vec_y) not vec_x = vec_y to pass values

Just some java 101, in case someone doesn’t know this or keeps forgetting.

As an example, you may want to make breadcrumbs for some pathfinding. You get a certain spatials’ location every couple of frames and add it to a collection so that you can backtrack.

If that’s what you want to do, create the vectors like this:

Vector3f tempLoc = new Vector3f(spatial.getLocalTranslation());

or if it’s already declared:


The value of tempLoc will be equal to the value of local translation at that time. If local translation was (1,2,1) it means tempLoc = (1,2,1). At least until you change it.

if you do:

Vector3f tempLoc = spatial.getLocalTranslation();

you end up with a vector that is “pointing” to the spatials loc vector, not its value. tempLoc will be set to (1,2,1), as in the previous example, but if spatial moves to (2,2,5) tempLoc changes to (2,2,5), etc.

This is why:

Q: If Java uses the pass-by reference, why won't a swap function work?

A: Your question demonstrates a common error made by Java language newcomers. Indeed, even seasoned veterans find it difficult to keep the terms straight.

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
1 Like