At present I have an ArrayList<Waypoint> where Waypoint is a simple class that is used to represent a position in an x/y-grid. Now I noticed that for one method I am always using the same instane of a Waypoint object — but I keep changing it’s values.
So if we have say a Waypoint WP which is initialised as X = 0, Y = 0 and I add that to the ArrayList, what exactly is saved? The WP element or just a copy that holds it’s values? Or, asked differently, if I would now increment the values of WP and save it to the ArrayList would the elements at position 0 and 1 in the ArrayList be exactly the same?
If yes, is there an “easy” way to create and save a copy a Waypoint element without having to create a new instance every time?
Thanks in advance!
Java works by references so the
Waypointobject, if not explicitly cloned, will be the same.If you keep a reference to it you can easily change its values while having these reflected into the same object contained in the list, just because they both reference to the same instance.
This will show the behavior you need:
You’ll see that output is
"20 40"as you’d expect.If you want to generate a new waypoint from the one you are starting from then you should define your own method and duplicate explicitly the object.
Doing
would just insert the same element twice, which is not what you are looking for. Instead:
would insert two different objects (assuming that
duplicateactually instantiates a different object withnew)