本文介绍了将数组引用分配给Java中的另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int a[]={1, 2, 3, 4, 5};
int b[]={4, 3, 2, 1, 0};
a=b;
System.out.println("a[0] = "+a[0]);
这显然显示了 a [0] = 4
,因为为 a
分配了对 b
的引用.
This displays a[0] = 4
as obvious because a
is assigned a reference to b
.
如果进行了如下修改
int a[]={1, 2, 3, 4, 5};
int b[]={4, 3, 2, 1, 0};
System.out.println("a[(a=b)[0]] = "+a[(a=b)[0]]); //<-------
然后,它显示 a [(a = b)[0]] = 5
.
为什么不使用此表达式- a [(a = b)[0]]
产生 4
,即第0个元素 b
,即使它看起来与先前的情况相同?
Why doesn't this expression - a[(a=b)[0]]
yield 4
, the 0 element of b
even though it appears to be the same as the previous case?
推荐答案
第二个表达式在数组索引器表达式内部具有赋值表达式.该表达式的计算结果如下:
The second expression features an assignment expression inside an array indexer expression. The expression evaluates as follows:
- 已选择索引器表达式的目标.那就是原始数组
a
- 首先通过将
b
分配给a
,然后在索引0处获取b
的元素来计算索引表达式 - 外部索引器的索引评估为
b [0]
- 将索引应用于
a
,并返回5
- 将
b
分配给a
生效.随后对a [i]
的访问将引用b
,而不是原始的a
.
- The target of the indexer expression is selected. That's the original array
a
- The index expression is evaluated by first assigning
b
toa
, and then taking the element ofb
at index zero - The index of the outer indexer is evaluated as
b[0]
- The index is applied to
a
, returning5
- The assignment of
b
toa
takes effect. Subsequent accesses toa[i]
will referenceb
, not the originala
.
本质上,您的单行表达式等同于以下两行代码段:
Essentially, your single-line expression is equivalent to this two-line snippet:
System.out.println("a[(a=b)[0]] = "+a[b[0]]); // Array reference completes first
a=b; // Array assignment is completed last
这篇关于将数组引用分配给Java中的另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!