62,620
社区成员
发帖
与我相关
我的任务
分享public class A {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}A a1 = new A();
A a2 = new A();
a1.setName("a1");
a2 = (A) a1.clone();
System.out.println(a1);
System.out.println(a2);
a2.setName("a2");
System.out.println("a1 name: " + a1.getName());
System.out.println("a2 name: " + a2.getName());



Object o = new Object();
Object o2 = o.clone();

克隆是object类的方法,你实现Cloneable只是告诉虚拟机这个类可以被克隆,你不实现Cloneable借口调用clone方法会报错吧
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
hashCode方法返回了这个内存地址的一个标记,然后转换为16进制打印。
native的hashCode方法屏蔽了这些实现的细节,但我们可以设想在同样的计算机环境Context下,这个分配的内存地址应该是相对稳定的(因为特定算法封装的嘛),所以你在重复的操作中,可以认为计算机的环境是相对稳定的,从而可以得到一个相对稳定的结果。
偶尔这个地址有变化很正常啊,谁知道你电脑里跑了多少线程,在哪个时间点污染了这个Context我没分了,求给分

Object类没有实现Cloneable接口 当然不能克隆 java中的类只要实现了Cloneable接口就能克隆

Effective Java,Item 11(第二版,54页)中专门说的这个问题 这是java中最反人类的设计,可能没有之一。具体的细节楼主可以去翻阅一下,给你贴出来最后的结论 Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.
给跪了 你好流弊啊