I think you’re confusing the concepts of variable declaration and object identity.
In the following code there are declared three variables “ammo1”, “ammo2” and “ammo3”. But there is only one object instance - the one created with the “new” keyword. In this code ammo1, ammo2 and ammo3 are all references to the same object. You might say that there is one Ammo which is known by three names.
Ammo ammo1 = new Ammo();
Ammo ammo2 = ammo1;
Ammo ammo3 = ammo1;
Likewise, in the following code a total of ten Ammo objects are created. Inside the first for-loop the “ammo” variable exists only a short while - it is created and destroyed on every loop. But the lifespans of the Ammo objects continue even after the loop, because they are added into the “ammos” collection. When all the ammos are printed in the latter loop, you will see that all the objects have a different identity (by default they will print as something like Ammo@123, Ammo@124, Ammo@125 etc.). Inside the first loop the Ammo objects are known by the variable name “ammo”, between the loops they don’t have a variable name, and in the latter loop they use the variable name “a”.
Collection<Ammo> ammos = new ArrayList<Ammo>();
for (int i = 0; i < 10; i++) {
Ammo ammo = new Ammo();
ammos.add(ammo);
}
for (Ammo a : ammos) {
System.out.println(a);
}
Modify your Ammo class to look as below, and then run the above code. Experiment with it and read about the basics of object-oriented programming until you understand fully why it prints:
I’m Ammo #1
I’m Ammo #2
I’m Ammo #3
…
I’m Ammo #10
Ammo.java:
public class Ammo {
private static int nextNumber = 1;
private final int number;
public Ammo() {
number = nextNumber;
nextNumber++;
}
public String toString() {
return "I'm Ammo #" + number;
}
}