深入引用的例子
class Demo{
int x=10;
}
public class Demo1 {
public static void main(String args[]){
Demo d=new Demo();
d.x=30;
fun(d);
System.out.println(d.x);
}
public static void fun(Demo temp){
temp.x=100;
}
}
public class Demo2 {
public static void main(String args[]){
String str = "hello";
fun(str);
System.out.println(str);
}
public static void fun(String temp){
temp="world";
}
}
以上两个例子第一个输出是100第二个是hello,不是说对内存一旦定下来就不可修改么?为什么好像第一个例子的x可修改,第二个的str不可修改,大神们求助啊!
[解决办法]
你说的内存不可修改的应该是指字符串吧?字符串一旦定下来就不能修改,若要储存不同的字符串,就要重新开辟内存空间
class Demo{
int x=10;
}
public class Demo2 {
public static void main(String args[]) {
String str = "hello";
System.out.println("hello hashcode:"+str.hashCode());
fun(str);
System.out.println("finally hashcode:"+str.hashCode());
System.out.println(str);
}
public static void fun(String temp) {
System.out.println("before change hashcode:"+temp.hashCode());
temp = "world";
System.out.println("after change hashcode:"+temp.hashCode());
}
}