java对象根据某几个元素去重

直接上代码,用的比较多
方式用用Set特性去重,但关键在于对象的equals()和hashCode()两个方法的重写
之所以在重写equals()的情况下,还需要重写hashCode()方法,是因为HashSet/HashMap/Hashtable 类存储数据时,都会根据存储对象的 hashCode 值来进行判断是否相同的

    public static void main(String[] args) {
        List<BoardVo> boardTyprCount=new ArrayList<>();
        boardTyprCount.add(new BoardVo(0,8));
        boardTyprCount.add(new BoardVo(0,8));
        boardTyprCount.add(new BoardVo(1,16));
        boardTyprCount.add(new BoardVo(1,16));
        System.out.println("--------没有去重的----------");
        for (BoardVo b: boardTyprCount ) {
            System.out.println(b.toString());
        }

        System.out.println();
        System.out.println("-----------去重后的--------------");
        Set<BoardVo> set=new HashSet<>();
        set.addAll(boardTyprCount);
        for (BoardVo b:set) {
            System.out.println(b.toString());
        }
    }

结果:
在这里插入图片描述
BoardVo类

public class BoardVo {

private  Integer index;
private  Integer type;

public BoardVo() {
}

public BoardVo(Integer index, Integer type) {
    this.index = index;
    this.type = type;
}

public Integer getIndex() {
    return index;
}

public void setIndex(Integer index) {
    this.index = index;
}

public Integer getType() {
    return type;
}

public void setType(Integer type) {
    this.type = type;
}


@Override
public String toString() {
    return "BoardVo{" +
            "index=" + index +
            ", type=" + type +
            '}';
}
//关键在于这两个方法的重写------------重点!!!!!
@Override
    public boolean equals(Object obj) {
    BoardVo boardVo=(BoardVo)obj;
    //这里因为参数定义的是Integer包装类,所以比较不能用==,要用equals(),否则当参数不在(-127,,128)之间的话它自动拆箱后是会报错的
    //另外你要多少个参数可以决定这里就写多少个参数相等条件,同时下面的额hashCode()方法也要保持参数一致
    return index.equals(boardVo.index) && type.equals(boardVo.type);
}
@Override
public int hashCode() {
    String str=String.valueOf(index)+String.valueOf(type);
    return str.hashCode();
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值