我有一个简单的问题要问,我有Product类,其中的字段如下:

private Integer id;
private String category;
private String symbol;
private String desc;
private Double price;
private Integer quantity;

我想根据ID从LinkedHasSet中删除重复项,例如,具有相同ID但数量不同的产品将被添加到集合中,我想删除(更新)具有相同ID的产品,并且它将通过我的对象的唯一ID进行操作要做到这一点?

例如
产品:id = 1,类别= CCTV,符号= TVC-DS,desc =简单摄像机,价格= 100.00,数量= 1
产品:id = 1,类别= CCTV,符号= TVC-DS,desc =简单摄像机,价格= 100.00,数量= 3

不会添加到集合中

我的代码:
    public void setList(Set<Product> list) {
    if(list.isEmpty())
        this.list = list;
    else {
        this.list.addAll(list);
        Iterator<Product> it = this.list.iterator();
        for(Product p : list) {
            while(it.hasNext()) {
                if(it.next().getId() != p.getId())
                    it.remove();
                    this.list.add(p);
            }
        }
    }
}

最佳答案

所有Set实现都删除重复项,并且LinkedHashSet也不异常(exception)。

根据其equals()方法,重复项的定义是两个彼此相等的对象。如果尚未在equals类上覆盖Product,则仅将相同的引用视为相等-不会将不同的实例具有相同的值。

因此,您需要为您的类添加更加具体的equals(和hashcode)实现。有关一些示例和指南,请参见Overriding equals and hashcode in Java。 (请注意,您还必须覆盖hashcode,否则您的类在哈希集中将无法正确运行。)

10-01 21:43
查看更多