[java] Inventory Recursion

Started by
3 comments, last by rip-off 12 years, 6 months ago
I have:



switch(item.getType()) {
case empty:
inventoryList.add(new Item(Item.ItemType.empty, quantity)); break;
case demoItem:
inventoryList.add(new DemoItem(Item.ItemType.demoItem, quantity)); break;
case demoItem2:
inventoryList.add(new DemoItem2(Item.ItemType.demoItem, quantity)); break;
default: System.out.println("Please define a create case for new item: " + item.getType().toString() + "."); break;
}


Every time I extend my class item I have to add another case for that particular item type. How can I do this more recursively?

I've looked at the clone() and .getClass().getConstructor methods but can't seem to get the syntax quite right.
Advertisement
why not just use a addItem method. You jsut have to creat your Item object on the outside and pass it in.

why not just use a addItem method. You jsut have to creat your Item object on the outside and pass it in.


I'm already doing this, I pass in any Item or subclass of Item. The code then needs to copy the item or make a new item based on the items subclass constructor.



private int Create(Item item, int quantity) throws InventoryFullException {
if(inventoryList.size() < noSlots) {
switch(item.getType()) {
case empty:
inventoryList.add(new Item(Item.ItemType.empty, quantity)); break;
case demoItem:
inventoryList.add(new Item(Item.ItemType.demoItem, quantity)); break;
default: System.out.println("Please define a create case for new item: " + item.getType().toString() + "."); break;
}

if(quantity > item.getStackSize()) {
return item.getStackSize() - quantity;
}
else {
return 0;
}
}
else {
return quantity;
}
}
why do u want to copy it? just use the clonable interface then
If item is not a class hierarchy, then you don't need to switch. You can just pass item.getType() to the constructor of the new Item.

private int Create(Item item, int quantity) throws InventoryFullException {
if(inventoryList.size() < noSlots) {
inventoryList.add(new Item(item.getType(), quantity));

if(quantity > item.getStackSize()) {
return item.getStackSize() - quantity;
}
else {
return 0;
}
}
else {
return quantity;
}
}

If it is (or will be) a hierarchy, what trouble is the clone method causing you? Are you implementing Cloneable? If you want deep copy semantics, have you written a custom clone() implementation. Remember to use a covariant return type (public Item clone()) to avoid ugly casts elsewhere in your code.

This topic is closed to new replies.

Advertisement