Array replication: An Example of passing references in java

Source: Internet
Author: User

First, let's look at the following two procedures:

(1 ).
1 int [] a = {1, 2, 3, 4}; 2 int [] B = new int [4]; 3 B =;
(2 ).
1 int [] a = {1, 2, 3, 4}; 2 int [] B = new int [4]; 3 int I = 0; 4 for (int num: a) {5 B [I ++] = num; 6}
After the value is assigned, all values of array B are {1, 2, 3, 4}But there is a substantial difference between the two methods. First, the array initialization process is as follows: Int [];First define an array name A, And then AThis variable is added to the stack. Of course there is no AInitialization, so AIs an empty reference. For Int [] a = {1, 2, 3, 4}First, define a variable. AAnd set AStack, and create an object in the heap area. {1, 2, 3, 4}, And finally create AObject {1, 2, 3, 4}. Second, value transfer and reference transfer, the first method is actually changed AReferences, A, BReferencing the same object also produces a negative consequence, BThe referenced object is no longer referenced, and a piece of memory garbage is generated. As shown in: the second method is BThe value of the referenced memory region is not changed. B. Do not use the reference transfer method to copy an array. This will not only generate memory garbage, but will also change the original array if not appropriate.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.