将相同的对象添加到多个arraylists [英] Add same object to multiple arraylists

查看:103
本文介绍了将相同的对象添加到多个arraylists的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发游戏并注意到向两个arraylists添加一个对象然后更新其中一个并不会更新另一个。是否有可能解决这个问题?

I'm working on a game and noticed that adding an object to two arraylists and then updating one of them doesn't update the other. Is it possible to solve this?

我有一个列表,列出了渲染时循环的所有图块。但我还想在我的库存类中找到一个插槽列表(扩展Tile),而不是循环所有游戏磁贴以获得库存插槽。

I have a list of all tiles which is looped though when rendering. But I also want a list of slots(extends Tile) in my inventory class instead of looping though all game tiles to get the inventory slots.

我有两个列表:游戏.tiles和Inventory.slots

I have two lists: Game.tiles and Inventory.slots

这是我添加插槽的地方(库存类):

This is where I add slots (Inventory class):

for(int i = 0; i< 16; i++){
Slot slot = new Slot();
Game.tiles.add(slot);
slots.add(slot);
}

这是我修改插槽的地方(库存类):

And this is where I modify slots (Inventory class):

for(int i = 0; i< 16; i++){
slots.get(i).visable = false;
}

问题是插槽列表中插槽的数据更新但没有对于Game.tiles列表中的相同插槽。

The problem is that the data updates for the slot in the slots list but not for the same slot in the Game.tiles list.

完整库存类: http://pastebin.com/KS5BNB3F

推荐答案

将对象添加到两个不同的 ArrayList ,实际上只添加了对象的引用。因此,如果您修改对象,它将同时反映在两个列表中。请参阅以下代码段:

When you add an object to two different ArrayList, you are actually adding only references to the object. So if you modify the object, it will reflect in both the lists at the same time. See the following code snippet:

public class Clazz{
   private Integer d = 0;
   public static void main(String[] args) throws Exception {
       Clazz obj = new Clazz();
       List<Clazz> list1 = new ArrayList<Clazz>();
       List<Clazz> list2 = new ArrayList<Clazz>();
       list1.add(obj);
       list2.add(obj);
       obj.d = 15;
       System.out.println(list1.get(0).d); //prints 15
       System.out.println(list2.get(0).d); //prints 15
   }
}

这篇关于将相同的对象添加到多个arraylists的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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