LinkedHashSet remove duplicates object

前端 未结 5 1988
梦毁少年i
梦毁少年i 2021-01-13 06:58

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         


        
5条回答
  •  悲&欢浪女
    2021-01-13 07:46

    I won't give you straight answer, but a couple of advices.

    1. If you want to put Product in a Set you need to implement its equals() and hashCode() methods.
    2. When implementing 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.
    3. Normally in situation like this only ID is taken into account. In that case you shouldn't have two 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).
    4. 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.

提交回复
热议问题