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]);
}
}
答案 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);
}
}