是否可以从包含自定义类型元素的List中删除重复项?

时间:2015-05-20 10:04:00

标签: java

这是我的代码

package com.dto;

public class OtherBrands {

    private String otherbrandsname ;
    public String getOtherbrandsname() {
        return otherbrandsname;
    }
    public void setOtherbrandsname(String otherbrandsname) {
        this.otherbrandsname = otherbrandsname;
    }
    public String getDealerBrandQty() {
        return dealerBrandQty;
    }
    public void setDealerBrandQty(String dealerBrandQty) {
        this.dealerBrandQty = dealerBrandQty;
    }
    private String dealerBrandQty ;

}

import java.util.ArrayList;
import java.util.List;
import com.dto.OtherBrands;

public class Test {
    public static void main(String args[])
    {
        List < OtherBrands > otherBrandsList = new ArrayList < OtherBrands > ();
        for (int k = 0; k < 3; k++) {
            OtherBrands otherbrands = new OtherBrands();
            String otherbrandsname = "Test";
            String dealerBrandQty = "2";
            otherbrands.setOtherbrandsname(otherbrandsname);
            otherbrands.setDealerBrandQty(dealerBrandQty);
            otherBrandsList.add(otherbrands);
        }

        for(int i=0;i<otherBrandsList.size();i++)
        {
            System.out.println(otherBrandsList.get(i).getOtherbrandsname()+"\t"+otherBrandsList.get(i).getDealerBrandQty());

        }
    }
}

当我运行这个程序时,结果是:

Test    2
Test    2
Test    2

如果键和值相同,则应将其视为重复

是否可以从列表中删除重复项?

2 个答案:

答案 0 :(得分:4)

首先,如果您想避免重复,请使用HashSet而不是List。

其次,您必须覆盖hashCodeequals,以便HashSet知道您认为哪些元素彼此相等。

public class OtherBrands {

    @Override
    public boolean equals (Object other)
    {
        if (!(other instanceof OtherBrands))
            return false;
        OtherBrands ob = (OtherBrands) other;
        // add some checks here to handle any of the properties being null
        return otherbrandsname.equals(ob.otherbrandsname) &&
               dealerBrandQty.equals(ob.dealerBrandQty);
    }

    @Override
    public int hashCode ()
    {
        return Arrays.hashCode(new String[]{dealerBrandQty,otherbrandsname});
    }
}

答案 1 :(得分:1)

您应该使用HashSet而不是ArrayList,因为它可以保证删除重复的项目。它只需要您在hashCode()类中实现equals()OtherBrands方法。

作为提示,如果您使用Eclipse:您可以使用编辑器菜单功能'Source / Generate HashCode and Equals'生成这两种方法。然后选择所有属性,这些属性定义OtherBrands项的名称(名称,数量)。