Add same object to multiple arraylists

2020-05-08 07:30发布

问题:

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?

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.

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;
}

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.

Full inventory class: http://pastebin.com/KS5BNB3F

回答1:

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
   }
}


回答2:

Create an object instance, add it to both arrays. Then those arrays will have the same references. This means that updating your object would result in it updated in both arrays.



标签: java arrays