Java: Duplicate objects getting added to set?

后端 未结 3 1129
既然无缘
既然无缘 2020-12-15 06:32

If I run the below code then the output is 2 which means that the set contains 2 elements. However I think that set should contain 1 since both the objects are equal based o

3条回答
  •  暖寄归人
    2020-12-15 06:55

    The @Overrides annotation is to override the method with the same name in the super class".

    @Override
    public int hashCode() {
        return a;
    }
    
    @Override
    public boolean equals(Object obj) {
        return (obj instanceof Alpha && ((Alpha) obj).a == this.a);
    
    }
    
    @Override
    public String toString() {
        return "Alpha : " + a;
    }
    

提交回复
热议问题