LinkedHashSet remove duplicates object

前端 未结 5 2023
梦毁少年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:31

    The code seems to be adding to the list twice. Once during the addAll() call then once again during the iteration. In this case I believe the second iteration would suffice. The comparison should also be modified to use equals instead of ==

    public void setList(Set list) {
        if(list.isEmpty()) 
            this.list = list;
        else {
            //this.list.addAll(list); Do not add all
            Iterator it = this.list.iterator();
            for(Product p : list) {
                while(it.hasNext()) {
                    if(it.next().getId().equals(p.getId()))
                    {
                        this.list.add(p);
                    }   
                }
            }
        }
    }
    

提交回复
热议问题