为什么类被@Data修饰后,clone的对象和原来的对象具有相同的hashcode?

最近在敲代码时,发现了一个奇怪的现象?

@Data
public class Person implements Cloneable{
    private Integer num;
    private String jobName;

    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person)super.clone();
    }
}

person在实现了Cloneable后,调用clone方法生成的对象具有与源对象一样的hashcode。

我们知道使用Object的clone方法会返回一个新对象,这个对象与源对象相同,只是地址不同,所以代表地址的hashcode应该是不一样的。

后来查看了一下编译生成target文件夹中的Person类才知道,被@Data修饰的类会提供类的get、set、equals、hashCode、toString方法。而重写的hashcode方法是根据类的属性的值来计算hashcode,所以拷贝后两者的hashcode才会一样。

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $num = this.getNum();
        int result = result * 59 + ($num == null ? 43 : $num.hashCode());
        Object $jobName = this.getJobName();
        result = result * 59 + ($jobName == null ? 43 : $jobName.hashCode());
        return result;
    }

明白这一点后,我将@Data改用成@ToString、@Setter、@Getter,这个问题就解决了。

@Setter
@Getter
@ToString
public class Person implements Cloneable{
    private Integer num;
    private String jobName;

    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person)super.clone();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_47025878/article/details/129101631
今日推荐