1
\$\begingroup\$

Why do people use this:

public void set(Vector2 v) {
    this.vector2 = v.cpy();
}

insted of just using:

public void set(Vector2 v) {
    this.vector2 = v;
}

What I don't know that I should know?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The first one is creating a new object and assigning its reference to a variable. The second one is just assigning an object to a variable, so you would just end up with 2 variables pointing to the same object. So modifying 1 object's properties (for example x), would modify the other object as well. \$\endgroup\$
    – dimitris93
    Commented Jul 15, 2015 at 9:22

1 Answer 1

3
\$\begingroup\$

If you would follow the second strategy, changes made to the Vector that got passed as parameter "v" will also be made to "vector2", since they are the same object.

You should have a look at this question: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

In Java every object is an reference, so you need to copy, for example your Vector2 Object, if you don't want to introduce crazy ass bugs.

A better alternative is to just set x and y to the x and y values of the vector you want to copy from.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Read the second answer on that question by Scott Stanchfield. That one explains it best and the question is actually referring to his blog post. But then again I still introduce "crazy ass bugs" sometimes. \$\endgroup\$
    – Madmenyo
    Commented Jul 17, 2015 at 18:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .