ArrayList list = new ArrayList (20); list expands several __java interviews

Source: Internet
Author: User

ArrayList list = new ArrayList (20); The list in is expanded several times ()

A 0 B 1 C 2 D 3

Answer: A

dynamic expansion mechanism of ArrayList

Initialization: There are three different ways

The default constructor will initialize the internal array with the default size: public ArrayList ();

Constructs with a ICollection object and adds the elements of the collection to the Arraylist:public ArrayList (collection<? extends e> c)

Initializes an internal array with the specified size: public ArrayList (int initialcapacity)


Here we focus on the implementation process of the parameterless constructor:

The code has an initial capacity of 0.  In the previous jdk1,6, the initial capacity was 10. conditions for expansion:

According to the minimum required capacity mincapacity to compare the capacity length of arrays, if mincapactity is greater than or equal to the array capacity, expansion is required. (If the actual storage array is an empty array, the minimum required capacity is the default capacity)
To achieve expansion:
In the JDK7, use the >> bitwise operation to move one position to the right. Capacity equivalent to 1.5 times times the expansion;

Example: Add 20 elements to ArrayList

10 (default) object space is assigned the first time an element is inserted. The expansion will then increase by 1.5 times times.

That is, when adding the 11th data, ArrayList continue to expand into 10*1.5=15;

When the 16th data is added, the continuous expansion becomes 15 * 1.5 = 22;


Summarize:
In JDK1.7, if the initial array capacity is 0, the capacity is really allocated when the real arrays are added.

In JKD1.6, the initial array capacity is 10 if it is constructed by means of an parameterless construct. The capacity is 1.5 times times plus 1 after each expansion through the copeof. The above is the principle of dynamic expansion.

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.