public void method (AmazingObject obj) {
HashMap<Integer, AmazingObject> hashmap = new HashMap<>();
for (int i = 0; i < 5; i++) {
obj = new AmazingObject();
hashmap.put(i, obj);
}
for (int i = 0; i < 5; i++) {
System.out.println(hashmap.get(i).toString());
}
}
I wrote this code out and see that the array contains completely different objects for every element. If I understand this properly:
1) The method accepts a reference copy of an AmazingObject instance.
2) I assign a new address to that reference type by using the new keyword.
3) Another reference copy containing my new address is thrown into the Hashmap.
Therefore, none of the previous values are overwritten. Is the reason for this behavior that Java is pass by reference copy and not pass by reference? I would have expected every element in the array to point to the exact same object at the end (i.e. the last assigned object).