So I’m reading this game tutorial and there is code to make arrayLists with aliens/missiles disappear upon collision.
ArrayList ms = craft.getMissiles();
for (int i = 0; i < ms.size(); i++) {
Missile m = (Missile) ms.get(i);
Rectangle r1 = m.getBounds();
for (int j = 0; j<aliens.size(); j++) {
Alien a = (Alien) aliens.get(j);
Rectangle r2 = a.getBounds();
if (r1.intersects(r2)) {
m.setVisible(false);
a.setVisible(false);
}
}
}
In the last loop, m.setVisible(false) and a.setVisible(false) make that specific alien/missile invisible but ‘a’ and ‘m’ are not part of the ArrayList they’re ArrayList objects pulled out and casted into ‘a’ and ‘m’ yet the code seems to work fine given that the coder does not insert the ‘a’ or ‘m’ object back into its specific spot in the arraylist (or update its corresponding object in the arraylist).
Which makes me think, are ‘a’ and ‘m’ referenced by address to the i-th object in the arraylist as opposed to being copies?
Yes. They’re references. Any time you say
in Java,
ais a reference, not the actual object (a common source of confusion).When you use a standard collection, getting an element from that collection will return the reference to the contained object. Consequently it’s trivial to iterate through a collection and perform changes on the contained objects.