java - Automatically adding every Class object constructed into an ArrayList -
i'm still new in learning java , i'm in need of way put every object constructed class arraylist can access later.
here item
class:
import java.util.arraylist; import java.util.*; public class item { private string name; private int quantity; private arraylist<item> allitems = new arraylist<item>(); //the arraylist i'm trying fill every item object /** * constructs item of given name , quantity * @param name item name * @param quantity how of item player has */ public item(string name, int quantity) { this.name = name; this.quantity = quantity; } /** * @return item name */ public string getitemname() { return name; } /** * @return quantity of item */ public int getquantity() { return quantity; } /** * @return list of items have quantity > 0 */ public arraylist<item> getinventory() { arraylist<item> inventory = new arraylist<item>(); for(item : allitems) { if(i.getquantity() > 0) inventory.add(i); } return inventory; } }
how can add item
object allitems
every time 1 constructed?
first, arraylis must static shared between instances. otherwise, have different variable per instance.
more info on instance/class members here.
private string name; private int quantity; private static arraylist<item> allitems = new arraylist<item>();
then, can add created instance in constructor, refering 'this'.
public item(string name, int quantity) { this.name = name; this.quantity = quantity; allitems.add(this); }
Comments
Post a Comment