【发布时间】:2014-07-14 17:54:26
【问题描述】:
问题基于以下代码:
class Car implements Cloneable
{
//Relevant constructor
String name;
int wheels;
Car another;
public Object clone()
{
/*DEEP
Car n = new Car(this.name,this.wheels);
n.another = new Car(this.another.name,this.another.wheels);
return n;
*/
return super.clone() ;
}
}
main(String[] args)
{
Car c1 = new Car("merc",4);
c1.another = new Car("baby merc",55);
Car c2;
c2 = (Car)c1.clone();
//PART 1
//HERE I TRY TO CHANGE object c2's another's name to "Han"
System.out.println(c1.another.hashCode() == c2.another.hashCode());
/*POINT 1*/ c2.another.name = "Han";
System.out.println(c1.another.hashCode() == c2.another.hashCode());
//PART 2
String s = new String("gG");
System.out.println(s.hashCode());
s ="JAJA";
System.out.println(s.hashCode());
}
- 在第 1 部分中,我更改了对象
c1的成员another的成员名称 与众不同。 - 在第 2 部分中,我创建了一个字符串,检查其哈希码,然后更改其值,然后再次检查其有代码。
输出:
true
true
3264
2269358
- 我不明白当我更改
c2.another.name然后c1.another.name也指向前一个字符串“baby merc”所占用的完全相同的旧位置。 POINT1 处的操作不应该导致返回新的参考位置,从而导致c2.another指向新位置而c1.another指向旧位置吗? - 为什么当我将一个字符串指向一个新的
细绳?分配了堆中的新区域并引用变量
保存新位置的引用。在
c1和c2的情况下 即使修改后参考位置也不会改变!为什么?
【问题讨论】:
-
车内的车?
-
可能被拖走?
-
请显示
clone和hashCode方法(如果它们被覆盖)。 -
@Henry
hashCode和clone未被覆盖。这是一个浅克隆。所以我只是在clone()方法中返回super.clone(); -
请不要以改变其含义的方式更改问题。