x.clone().equals(x)如何为True

Raj*_*l D 0 java clone equals

我尝试过这个实现,但是对于类x来说我是假的

x.clone().equals(x)
Run Code Online (Sandbox Code Playgroud)

X级:

public class X implements Cloneable{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    protected Object clone()throws CloneNotSupportedException {
        return super.clone();       
    }

}
Run Code Online (Sandbox Code Playgroud)

主要课程:

public class ObjectCloneCopy {
  public static void main(String[] args) throws CloneNotSupportedException {
    X x = new X();
    System.out.println("x.clone().equals(x) - " + x.clone().equals(x));
  }
}
Run Code Online (Sandbox Code Playgroud)

是否必须重载hashcode()和equals()以获得此True?

如果不重写这些方法,这个陈述如何给出真实的?

X x1 = x;
x1.equals(x)
Run Code Online (Sandbox Code Playgroud)

解释这可能是真的,我已经在这个链接中看到了

Ruc*_*era 5

您需要在类中覆盖equals()hashCode()方法X.

否则你无法从中获得正确的结果 x.clone().equals(x)