记录今天HashSet去重及equals的坑

众所周知,HashSet能够去重,可是在实际运用中,可谓踩坑连连。web

1. HahsSet数据,做为对象的字段,重写equals以后:ide

@Override
    public boolean equals(Object obj){
    	if(!(obj instanceof PushMsgRule)) {
            return false;
        }
    	PushMsgRule b = (PushMsgRule)obj;
        if(this.getId().equals(b.getId())) {//这里用 == 不能断定“123faiwebgwergbuiwe3123r2” == “123faiwebgwergbuiwe3123r2” 为true
            return true;
        }
        return false;
    }

this.getId().equals(b.getId())也要用equalsui

2. 附正常对象的equals 和hashcode方法this

    @Override
    public boolean equals(Object obj){
        if(!(obj instanceof PushMsgRule)) {
            return false;
        }
        PushMsgRule b = (PushMsgRule)obj;
        if(this.getId().equals(b.getId())) {
            return true;
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        return this.id.hashCode();
    }spa

相关文章
相关标签/搜索