I have simple question to you, I have class Product that have fields like this:
private Integer id;
private String category;
private String symbol;
private S
I won't give you straight answer, but a couple of advices.
Product
in a Set
you need to implement its equals()
and hashCode()
methods.equals()
you will have to decide what "equality" for a Product
means, (Set
can contain only one instance in terms on "equality"). For instance, if two Product
instances are "equal" is it enough if they have the same ID or should we also take quantity into account?. It's not easy to answer this question in your case, but please read on.Product
instances in memory with different quantities
, because one of them would represent a state that is incorrect (ie. particular product's quantity can be either 1 or 3, not both at a time).I think the design is not fully correct. Product
class in your case represents a general product description (including price), so quantity
doesn't really fit there. If someone can order a couple of copies of Product
I think you should create another class such as Order
or OrderLine
which specifies what product is ordered and the corresponding quantity, eg:
class OrderLine { private Product product; private Integer quantity; }
With design like this it's easy to answer question from point 2. Product.equals()
should compare the ID only, and OrderLine.equals()
both the product (ID) and quantity.