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?
playerInventoryis anArrayList. How is that you calladdToInventory()method on it?