I am creating an array list in a class called Inventory. Here there are methods to add to, delete and get the list. I create a new array list in a new class called combat and set this array list to the one in the Inventory class with a get method.
This is the inventory class part:
private ArrayList<String> inventory;
public Inventory() {
this.inventory = new ArrayList<>();
}
public void addToInventory(String item) {
inventory.add(item);
System.out.println("A " + item + " has been added to your inventory");
printInventory();
}
public void removeFromInventory(String item) {
inventory.remove(item);
}
public ArrayList<String> getInventory() {
return inventory;
}
This is in the Combat Class:
private Inventory inventory = new Inventory();
private ArrayList<String> playerInventory = inventory.getInventory();
public Combat() {
}
@Override
public void setPlayerHit() {
System.out.println(playerInventory);
When I call the print playerInventory line, the arrayList returns []. Yet in the inventory class it has something in as I add an item to it shown in my launcher class:
playerInventory.addToInventory(item.getItem(9));
I can get this working using public fields but wanted to make use of encapsulation and use getters and setters. Could I possibly get some pointers please?
Just guessing here, but it sounds like you are using separate Inventory
objects in different parts of the code. They won't share the same internal inventory
array list and items added to one Inventory
object won't appear in the other. Make sure that the Inventory
object you are printing is the same one to which you have added items.
If you want a single global Inventory
object, you can use a singleton:
public class Inventory {
private static Inventory instance = new Inventory();
private ArrayList<String> inventory;
public static Inventory getInstance() {
return instance;
}
// private constructor to prevent extra copies of the inventory
private Inventory() {
inventory = new ArrayList<>();
}
...
}