Gos*_*sre 2 java arrays arraylist object
我有两个值,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);
Run Code Online (Sandbox Code Playgroud)
和一个ArrayList:
private ArrayList<EnemyInfo> activeEnemies = new ArrayList<EnemyInfo>();
Run Code Online (Sandbox Code Playgroud)
假设我将三个small_red和五个small_blue敌人加入其中activeEnemies.每当我想要更改数组中的变量时,例如:
activeEnemies.get(1).setActive(true); // change one of the small_red enemies
Run Code Online (Sandbox Code Playgroud)
small_red数组中的每个都被更改,而不仅仅是索引处的数据1.
Ric*_*gle 15
你每次向arraylist 添加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.
Run Code Online (Sandbox Code Playgroud)
small_red可以被认为是一个内存地址(虽然它比那更复杂),所以你要多次添加相同的内存地址(比如在现实生活地址簿中添加相同的内部地址).您从地址簿中获取地址的页面无关紧要; 信件去了同一所房子.
每次使用new关键字时,您都在创建对象的新实例,否则您只是传递对旧对象的引用.