黑马程序员技术交流社区
标题:
对于字符串和数组的引用赋值有些不解
[打印本页]
作者:
林其荣
时间:
2013-1-16 19:21
标题:
对于字符串和数组的引用赋值有些不解
本帖最后由 张向辉 于 2013-1-17 16:15 编辑
String String1[] = new String[]{"one"};
String String2[] = new String[1];
String2 = String1;
String2[0] = "two";
for(int x=0;x<String1.length;x++){
System.out.println(String1[x]);
}
复制代码
//打印出来的结果是 three two 我修改第二个数组的0角标元素后第一个数组的0角标元素的值也跟着变化了
String Str = new String("one");
String str1 = new String();
str1 = Str;
str1 = "two";
System.out.println(Str);
}
}
复制代码
//而打印这段代码却打印出one
//我想问的是同样是引用数据类型 ,那为什么String1[0] 的值就跟着变了,而Str的值却没变呢?
作者:
黑马刘杰
时间:
2013-1-16 19:34
String String1[] = new String[] { "one" };
String String2[] = new String[1];
//String2和String1同时指向一个堆地址,这个堆地址的值为“one”
String2 = String1;
//修改了堆中的数据
String2[0] = "two";
for (int x = 0; x < String1.length; x++) {
System.out.println(String1[x]);
}
String Str = new String("one");
//在栈中声明一个变量str1,它指向堆中的一个String对象
String str1 = new String();
//str1指向的字符串对象的值为“one”
str1 = Str;
//str1变量指向一个新的对象,对象值为“two”
str1 = "two";
System.out.println(Str);
复制代码
总结一下,String类型是不可变的,他是一个对象,对String类型赋值是新new出一个对象,再让它指向这个新的堆地址
作者:
高浩
时间:
2013-1-16 19:50
你的代码写的好凌乱,引用数据类型传递的是引用,在对内存中的相应地址,而访问是就是凭借这这个地址从堆内存中找,还有数组是通过下角标来访问数据的,要注意下角标的变化。
作者:
黄金龙
时间:
2013-1-17 00:09
本帖最后由 黄金龙 于 2013-1-17 00:12 编辑
class Demo12
{
public static void main(String[] args)
{
String String1[] = new String[]{"one"};
String String2[] = new String[1];
String2 = String1; ////2个数组都指向同一个引用 修改String2[0]的值就等于修改了String2[0]的值所以会打印 two
String2[0] = "two";
for(int x=0;x<String1.length;x++)
System.out.println(String1[x]);
show();//你的第二个代码我把他封装在这里了
}
//======================//
// ----------代码分割线-----
//======================//
static void show()
{
String str = new String("one");
String str1 = new String();
str1 = str;////这里的话str1 会指向一个新的引用而不是指向str这里的
str1 = "two";
System.out.println(str);//所以打印的是 one
}
}
复制代码
作者:
希望的曙光
时间:
2013-1-17 04:19
第一个是数值元素长度的循环取值
第二个是new对象的赋值
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2