Why does the cloned object have the same hashcode as the original object after the class is modified by @Data?

When typing code recently, I found a strange phenomenon?

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

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

After the person implements Cloneable, the object generated by calling the clone method has the same hashcode as the source object.

We know that using the clone method of Object will return a new object, which is the same as the source object, but the address is different, so the hashcode representing the address should be different.

Later, I checked the Person class in the compiled and generated target folder to know that the class modified by @Data will provide the get, set, equals, hashCode, and toString methods of the class. The rewritten hashcode method calculates the hashcode based on the value of the attribute of the class, so the hashcode of the two will be the same after copying.

    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;
    }

After understanding this, I changed @Data to @ToString, @Setter, @Getter, and the problem was solved.

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

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

Guess you like

Origin blog.csdn.net/weixin_47025878/article/details/129101631