public class Example {
String str = new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args) {
Example ex=new Example();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
System.out.println(ex.ch);
}
public void change(String str,char ch[]){
str="test ok";
ch[0]='g';
}
}
如上代码,运行的结果是 good and gbc 为什么是这样的结果,请高手帮忙,谢谢
String str = new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args) {
Example ex=new Example();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
System.out.println(ex.ch);
}
public void change(String str,char ch[]){
str="test ok";
ch[0]='g';
}
}
如上代码,运行的结果是 good and gbc 为什么是这样的结果,请高手帮忙,谢谢
解决方案 »
- 高手进来帮忙看看这个自编的小服务端程序哪里错了
- 一个关于JAVA对文件的输入输出问题,希望大侠们来给帮助~!!!!!!!!!!!!!!
- 怎么控制JTable的显示大小?
- 如何装一个String变量内容下载到客户端文件
- 我恳求指教:对同一个inputstream或者outputstream对象可否用不同的外包类进行多次包装并使用?请进来看看
- 这样的界面怎么做呢
- Jcreator pro怎么配置?请各位高手指点。
- Swing如何通过同一个按钮向任意不同文本框输入值?
- 一段很简单的类型转换代码,但就是不知道哪里错了
- 用notepad写源代码,保存Java文件后,不出现class文件
- jsp获取文本框的值,执行SQL查询结果
- 字符串操作
因为数组ch[]传过去的是引用,所以change成功
String传过去的是"good"的一份拷贝,所以change不会影响到那个str对象
{
String str = new String("good");
char[] ch = {'a','b','c'};
public static void main(String[] args)
{
Example ex=new Example();
//ex.change(ex.str,ex.ch);
//System.out.print(ex.str+" and ");
//System.out.println(ex.ch);
Point pt = new Point(1,2);
ex.change(pt,ex.ch);
System.out.println(pt);
System.out.println(ex.ch);
}
public void change(Point pt,char ch[])
{
//str="test ok";
pt.x = 100;
pt.y = 200;
ch[0] = 'g';
}
}class Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public String toString()
{
return x+","+y;
}
}
数组的引用“ch”确实是保存在栈内存的,但是他的值'a','b','c'是保存在堆内存中的
调用方法时,数组传过去的引用就是这个引用“ch”,所以能修改
但是传递String的引用时,其实系统又在堆内存中重新生成了一个String对象,值也是"good",但是此时是另外一个引用,即和之前的str不是同一个引用,所以调用方法时实际上传递的是这个新的引用,被修改的也是这个新的引用指向的对象。
不好意思,说的好像有些乱,你可以看一下孙鑫的视频
是关于对象与数组的内存模型以及函数调用是的参数传递的第4课C、第4课D:
http://tech.163.com/special/00091T71/javashipin.html