Getting unexpected return value when appending to array

Yes, if you’re interested it’s more clear when you look at this behaviour in the context of c++. What Processing is doing in the background is basically how pointers/references are used in c++. Instead of passing the actual object, or making a copy of the object, processing uses “shortcuts” to the variable as it were.
When you declare a new variable Processing allocates a little bit of memory. However, when you then start passing it around, different things can happen. For simple datatypes, eg. floats, ints, char — anything that isn’t capitalised Processing will copy the actual thing, but for anything else (including a String) when assigned or passed into a function, it will send a reference to the object. So when you appended threeCards in the example above, you were actually appending a shortcut to the same single object, linking the same threeCards object to each slot in the array. When you moved the declaration and initialisation of the object inside the for loop, you actually made a new instance for each slot in the array.

Luckily, and unlike c++, you don’t have to worry about these objects being created and lingering around. Processing/Java will detect when objects aren’t used anymore and free up their memory. Ie. an object declared/created inside a for loop will persist if you assign it / refer to it from a place in an array like we did above. Had you not appended it to the array, Java would’ve killed the unused threeCard instances silently in the background. Quite murderous.

Lastly, the behaviour as described below you can totally use to your advantage. Share a single object to multiple instances through functions and/or constructor to other objects and you can adjust their behaviour from a single place afterwards.

1 Like