Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Issue

I have two values, small_red and small_blue:

private EnemyInfo small_red = new EnemyInfo("Red Fighter", Core.jf.getToolkit().createImage(Core.class.getResource("/com/resources/ENEMY_01.png")), 10, 100, new Location(0, 0), false, 0);
private EnemyInfo small_blue = new EnemyInfo("Blue Fighter", Core.jf.getToolkit().createImage(Core.class.getResource("/com/resources/ENEMY_02.png")), 50, 100, new Location(0, 0), false, 0);

and an ArrayList:

private ArrayList<EnemyInfo> activeEnemies = new ArrayList<EnemyInfo>();

Let's say I add three of the small_red and five of the small_blue enemies into the activeEnemies. Whenever I want to change a variable inside the array, e.g.:

activeEnemies.get(1).setActive(true); // change one of the small_red enemies

every small_red in the array is changed, instead of just the one at index 1.

like image 807
Gosre Avatar asked Feb 26 '26 21:02

Gosre


1 Answers

You're adding 3 references to the same smallRed enemy each time to the arraylist.

To explain;

private EnemyInfo small_red; //I am a variable, I hold a reference to an EnemyInfo

new EnemyInfo(.....) //I create a new EnemyInfo object "somewhere" and return a reference to it so it can be used.

small_red can be considered a memory address (although its more complicated than that), so you're adding the same memory address several times (like adding the same house address to your real life address book). It doesn't matter what page you get the address from in your address book; letters go to the same house.

Every time you use the new keyword you are creating a new instance of an object, otherwise you're just passing around a reference to an old object.

like image 78
Richard Tingle Avatar answered Mar 01 '26 11:03

Richard Tingle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!