ArrayList 问题 [英] ArrayList Issue

查看:20
本文介绍了ArrayList 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个值,small_redsmall_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);

和一个 ArrayList:

and an ArrayList:

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

假设我将三个 small_red 和五个 small_blue 敌人添加到 activeEnemies 中.每当我想更改数组内的变量时,例如:

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

每一个 small_red 在数组中都被改变了,而不仅仅是索引 1 处的那个.

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

推荐答案

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

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

解释;

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

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.

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

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.

这篇关于ArrayList 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆