在Java中与Array混淆

时间:2016-08-17 05:58:39

标签: arrays methods

  1. 有人可以回答为什么这段代码的输出是225?你为什么不改变一个?
  2. 当您查看代码2时,当a传递给test()时,它完全改变了。我的问题是为什么在传递给test()时1号中的'a'没有改变而2号中的'a'改变了? 我是Java的初学者。
  3. 1

    public class Array1
    {    
        static void test(int[] a)
        {
            int[] b = new int[2];
            a = b;
            System.out.print(b.length);
            System.out.print(a.length);
        }
    
        public static void main(String[] args) 
        {     
            int[] a = new int[5];   
            test(a);   
            System.out.print(a.length);
        }
    }
    

    2

    public class Array2
    {
        static void test(int[] a) {
        int[] b = new int[2];
        for(int i =0; i< a.length; i++)
        {
           a[i]=1;
        }
    }
    
    public static void main(String[] args) 
    {   
        int[] a = new int[5];
        test(a);    
        for(int i =0; i< a.length; i++)
        {          
            System.out.print(a[i]);      
        }   
    }
    

2 个答案:

答案 0 :(得分:0)

让我们看一下案例1中逐步发生的事情

main:int[] a = new int[5];:在main中声明一个指向5个整数的数组的ref变量 main:test(a); :通过引用原始数组来调用test test:static void test(int[] a) {:声明一个ref变量a来保持对调用者数组的引用=&gt;测试中的a对原始数组的另一个引用 test:int[] b = new int[2];:在测试中将ref变量声明为2个整数的新数组 测试:a = b;:将测试点中的ref变量a设为新数组=&gt;原始数组与main

中的a变量不变

剩下的输出现在正常。

现在案例2:

main:int[] a = new int[5];:在main中声明一个指向5个整数的数组的ref变量 main:test(a); :通过引用原始数组来调用test test:static void test(int[] a) {:声明一个ref变量a来保持对调用者数组的引用=&gt;测试中的a是对原始数组的另一个参考 test:int[] b = new int[2];:在测试中将ref变量声明为2个整数的新数组
...
test:a[i] = 1;:由于a是对原始数组的引用,因此您将更改原始数组中的值。

输出现在应该清楚了。

答案 1 :(得分:0)

在第一个代码中你得到225:

以下是原因:

让地址为be - aa111

让b的地址为 - bb111

1)您正在更改测试方法中的a的地址,因此在测试方法中,地址将变为bb111。

2)但是你没有将a恢复到它恢复到aa111的原始地址的main方法。

3)如果从测试方法返回,你将获得222。

这是

的代码
    public class Array1
    {    
          static int[] test(int[] a)
          {
               int[] b = new int[2];
               a = b;
               System.out.print(b.length);
               System.out.print(a.length);
               return a;
          }
          public static void main(String[] args) 
          {     
               int[] a = new int[5];   
               a = test(a);   
               System.out.print(a.length);
          }
     }