2

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.

4

1 回答 1

15

您每次将 3 个对同一个smallRed 敌人的引用添加到数组列表中。

解释;

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可以被认为是一个内存地址(虽然它比这更复杂),所以你要多次添加相同的内存地址(就像在你的真实地址簿中添加相同的房子地址)。您从地址簿中的哪个页面获取地址并不重要;信件去同一所房子。

每次使用new关键字时,您都是在创建对象的新实例,否则您只是在传递对旧对象的引用。

于 2013-09-11T13:17:30.730 回答