tags:

views:

95

answers:

1

I just started messing with generics and I want to make sure I got this right, any help?

public interface Cart<T extends CartItem> {
    public void setItems(List<T> items);
    public List<T> getItems();
}

public interface CartItem {
    public BigDecimal getQty();
    public void setQty(BigDecimal qty);
    // more
}

public class CartService<T extends Cart<E>, E extends CartItem> {
    public void addOrReplaceItem(T cart, E newCartItem) {
     List<E> items = cart.getItems();
     int position = items.indexOf(newCartItem);
     if(position > -1) {
      E existingItem = items.get(position);
      existingItem.setQty(existingItem.getQty()
                                            .add(newCartItem.getQty()));
     } else {
      items.add(newCartItem);
     }
    }
}

public interface GroceryCart extends Cart<GroceryCartItemImpl>{
    // more
}

public interface GroceryCartItem extends CartItem {
    // more
}

public class GroceryCartItemImpl implements Serializable, GroceryCartItem {
    // more
}

public class GroceryCartImpl implements Serializable, GroceryCart {
    // more
}

Calling CartService:

GroceryCartImpl gc = ............
GroceryCartItemImpl gci = ........... 

CartService<GroceryCartImpl, GroceryCartItemImpl> cs = 
                   new CartService<GroceryCartImpl, GroceryCartItemImpl>();
cs.addOrReplaceItem(gc, gci);
+4  A: 

Your code looks good. @sudo noob was wrong with the statement "extends should be implements".

I agree with @sudo noob, you should change the lines:

GroceryCartImpl gc = ............
GroceryCartItemImpl gci = ...........

...with:

GroceryCart gc = ............
GroceryCartItem gci = ...........

But this has nothing to do with generics.

tangens
+1: More descriptive than my own, and I stand corrected on the implements. :)
_ande_turner_