Micor
Micor

Reputation: 1542

Is this a right way to put Java generics in action?

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);

Upvotes: 1

Views: 162

Answers (1)

tangens
tangens

Reputation: 39733

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.

Upvotes: 4

Related Questions