HelloMyCode 2019-10-28 17:17 采纳率: 0%
浏览 687

关于java数组引用传递的问题

class TestIt
{
    public static void main ( String[] args )
    {
        int[] myArray = {1, 2, 3, 4, 5};
        ChangeIt.doIt( myArray );
        for(int j=0; j<myArray.length; j++)
            System.out.print( myArray[j] + " " );
    }
}
class ChangeIt
{
    static void doIt( int[] z ) 
    {
        z = null ;
    }
}

输出的值是 1 2 3 4 5

为什么不报空指针错误?我的理解是地址指向null以后myArray就是null了,难道是z和myArray其实是【值传递?】,z和myArray指向同一个地址,然后只是z的地址值被赋值为null了,通过相同的地址改变地址中存放的内容才能真正改变myArray的值?不知道是否是这样理解的,请各位大神指点迷津。

以下代码为对比:

class Test
{
     static void doIt( int[] z ) 
    {
        for(int i=0;i<z.length;i++)
                z[i]=i+2;//单个赋值
    }
    public static void main ( String[] args )
    {
        int[] myArray = {1, 2, 3, 4, 5};
        Test.doIt( myArray );
        for(int j=0; j<myArray.length; j++)
            System.out.print( myArray[j] + " " );
    }
}

输出的值是2 3 4 5 6

class Test
{
     static void doIt( int[] z ) 
    {
        for(int num:z)
            System.out.print(num+" ");
        int[] temp={2,3,4,5};
        z=temp;//整体赋值
        System.out.println();
        for(int num:z)
            System.out.print(num+" ");
    }
    public static void main ( String[] args )
    {
        int[] myArray = {1, 2, 3, 4, 5};
        Test.doIt( myArray );
        System.out.println();
        for(int j=0; j<myArray.length; j++)
            System.out.print( myArray[j] + " " );
    }
}

输出的值:

1 2 3 4 5

2 3 4 5

1 2 3 4 5

  • 写回答

4条回答 默认 最新

  • _鹿慕溪水 2019-10-28 17:30
    关注

    你的数组传给了方法,你的z=null只是把z这个地址对应的值设为了null,也就是让z指向了null,而没有改变array内部的值,myArray指向的依然是你的数组,而这个数组的值并没有发生任何变化

    评论

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊