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

问题描述

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

和一个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.

推荐答案

您正在添加的每个时间到ArrayList 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.

每当你使用你创建一个对象的新实例关键字,否则你只是路过身边的老对象的引用时间。

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的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:58