急!!!有一个关于数组传参的程序,请帮助分析结果。。。谢谢!

lingyue666 2004-09-07 10:17:48
程序如下:
class ArrayArgument{

public static void main(String args[]){
int x[]={11,12,13,14,15};
display(x);
change(x);
display(x);
}
public static void change(int x[]){
int y[]={21,22,23,24,25};
x=y;

}

public static void display(int x[]){
for(int i=0;i<x.length;i++)
System.out.print(x[i]);
System.out.println("");
}
}
运行结果: 11,12,13,14,15
11,12,13,14,15
为什么没有改变数组x的值呢?

如果程序做些变动:将
x=y; 改成for(int i=0;i<x.length;i++)
x[i]=y[i]
则运行结果变为: 11,12,13,14,15
21,22,23,24,25
...全文
213 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
tongapple77837 2004-09-08
  • 打赏
  • 举报
回复
这样应该可以了:
class ArrayArgument{

public static void main(String args[]){
int x[]={11,12,13,14,15};
display(x);
change(x);
display(x);
}
public static void change(int x[]){
int y[]={21,22,23,24,25};
for(int m=0;m<5;m++)
{
x[m]=y[m];
}
}

public static void display(int x[]){
for(int i=0;i<x.length;i++)
System.out.print(x[i]);
System.out.println("");
}
}
tongapple77837 2004-09-07
  • 打赏
  • 举报
回复
java语言总是传值调用。方法不能修改传递给它的任何参数变量的内容!
对于public static void change(int x[]){
int y[]={21,22,23,24,25};
x=y;}
x在方法被调用结束后,x的值还是没有改变。
mor 2004-09-07
  • 打赏
  • 举报
回复
说不清为什么 :(

System.arraycopy(y, 0, x, 0, y.length);
kingfish 2004-09-07
  • 打赏
  • 举报
回复
public static void change(int x[])

相当与
int []temp = x;
...
temp = y;

你只能修改temp[i], 修改temp与你的x没有关系。
Dynamic 2004-09-07
  • 打赏
  • 举报
回复
你的问题用C++来表示就是:
int *x={11,12,13,14,15};
void chang(int *x){
x=y;
}

如果你要改变x指向的数组的值,就要改变*x, 而不是x, 如下:
int *x={11,12,13,14,15};
void chang(int *x){
*x=?;
*(x+1)=?;
...
}

hpy121 2004-09-07
  • 打赏
  • 举报
回复
这是JAVA语言非常特殊的问题之一;
应该每一本JAVA的入门书都有分析的!
shine333 2004-09-07
  • 打赏
  • 举报
回复
反正记住这么一句话:

传A改x才有用

而传A改A在方法里面有效,除了方法就没用
shine333 2004-09-07
  • 打赏
  • 举报
回复
这个跟
class A {
int x;
public void swappingTheObjectsAlwaysFailsOutsideTheMethod(A a1, A a2) {
A temp = a1;
a1 = a2;
a2 = temp;
}

public void swappingTheObjectsFieldsWorks(A a1, A a2) {
int temp = a1.x;
a1.x = a2.x;
a2.x = temp;
}

public static void main(String[] args) {
A swap1 = new A(); swap1.x = 1;
A swap2 = new A(); swap2.x = 2;
swappingTheObjectsAlwaysFailsOutsideTheMethod(swap1, swap2);
System.out.println(swap1.x);
swappingTheObjectsFieldsWorks(swap1, swap2);
System.out.println(swap1.x);
}
}

一个道理,数组(不管是不是int[])也是对象,每个数组元素相当于这个对象的一个字段
baffling 2004-09-07
  • 打赏
  • 举报
回复
gz
pillar110 2004-09-07
  • 打赏
  • 举报
回复
数组,对象,和接口都属于引用类型
把数组作为参数传递,传过去的只是它的一个引用,把这个引用指向新的数组,对原数组没有改变

public static void change(int x[]){
int y[]={21,22,23,24,25};
x=y; //如果x不是一个数组,而是一个对象的话,通过对传过来的引用(实际上是复制了一个引用)进行操作,会改变原来的对象,但是,你现在是把这个引用指向了新的对象,原对象不会改变。
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧