Table of Contents
Why is the initial capacity of HashMap 16?
Is the initial capacity of ArrayList 10?
Why is the initial capacity of ArrayList 10?
Home Java javaTutorial What is the reason why the initial capacity of ArrayList in Java is 10?

What is the reason why the initial capacity of ArrayList in Java is 10?

May 10, 2023 pm 02:19 PM
java arraylist

Why is the initial capacity of HashMap 16?

When talking about the initialization capacity of ArrayList, we must first review the initialization capacity of HashMap. Here is the Java 8 source code as an example. There are two relevant factors in HashMap: initialization capacity and loading factor:

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
 * The load factor used when none specified in constructor.
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
Copy after login

In HashMap, the default initialization capacity of the array is 16. When the data is filled to 0.75 of the default capacity When, it will be expanded by 2 times. Of course, users can also pass in the specified size during initialization. However, it should be noted that it is best to use a value of 2 to the nth power. If it is not set to 2 to the nth power, HashMap will also convert it, but it will require one more step.

Regarding the implementation principle of HashMap, I will not go into details here. There are already too many articles on the Internet about this. One thing we need to know is the algorithm of HashMap to calculate the key value coordinates, that is, by hashing the key value and then mapping it to the coordinates in the array.

At this time, ensure that the capacity of HashMap is 2 to the nth power, then bit operation can be used to directly operate the memory during hash operation without conversion to decimal, and the efficiency will be higher.

Generally, it can be considered that the reason why HashMap uses 2 to the nth power and the default value is 16, has the following considerations:

  • Reduce hash collisions;

  • Improve Map query efficiency;

  • Allocation is too small to prevent frequent expansion;

  • Excessive allocation wastes resources;

In short, the reason why HashMap uses 16 as the default value is to reduce hash collisions and improve efficiency.

Is the initial capacity of ArrayList 10?

Next, let’s first confirm whether the initial capacity of ArrayList is 10, and then discuss why it is this value.

Let’s first take a look at the source code of ArrayList initialization capacity in Java 8:

/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;
Copy after login

Obviously, the default container initialization value is 10. And from JDK1.2 to JDK1.6, this value is always 10.

Starting from JDK1.7, when initializing ArrayList, the default value is initialized to an empty array:

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
Copy after login

There must be friends here who say that the default value of ArrayList in Java 8 The initial size is 0, not 10. And you will also find something strange about the comments on the constructor method: construct an empty list with an initial capacity of 10. What the hell? It's obviously empty!

Reserve your doubts, let’s take a look at the add method of ArrayList first:

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
Copy after login

The ensureCapacityInternal method is called in the add method. When entering this method, it is an empty container at the beginning, so size=0Incoming minCapacity=1:

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
Copy after login

In the above method, the capacity is first calculated by calculateCapacity:

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
Copy after login

will find minCapacity is reassigned to 10 (DEFAULT_CAPACITY=10), pass in ensureExplicitCapacity(minCapacity);ThisminCapacity=10,

The following is the method body:

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
Copy after login

The grow method in the above code is used to handle expansion, expanding the capacity to 1.5 times the original size.

Understanding the above processing flow, we will find that essentially the initial capacity of ArrayList is still 10, but it just uses lazy loading. This is an optimization performed by Java 8 to save memory. Therefore, from beginning to end, the initial capacity of ArrayList is 10.

Let me mention one more benefit of lazy loading. When there are thousands of ArrayLists in the program, the default size of 10 objects means that 10 pointers (40 or 80) are allocated to the underlying array when created. bytes) and fill them with null values, an empty array (filled with null values) takes up a lot of memory. If you can lazily initialize an array, you can save a lot of memory space. The changes in Java 8 are for the above purpose.

Why is the initial capacity of ArrayList 10?

Finally, let’s discuss why the initial capacity of ArrayList is 10. In fact, it can be said that there is no reason, it just "feels" good, not too big, not too small, just right for the eyes!

First of all, when discussing HashMap, we said that the reason why HashMap chooses 2 to the nth power is more to consider the performance and collision of the hash algorithm. This problem does not exist for ArrayList. ArrayList is just a simple growing array, without considering optimization at the algorithm level. As long as it exceeds a certain value, it can grow. Therefore, theoretically speaking, the capacity of ArrayList can be any positive value.

The ArrayList documentation does not explain why 10 was chosen, but it is most likely due to the consideration of the best match between performance loss and space loss. 10. It’s not too big, not too small, it won’t waste too much memory space, and it won’t compromise too much performance.

If you have to ask why 10 was chosen in the first place, you may have to ask the author of this code "Josh Bloch".

If you observe carefully, you will also find some other interesting initialization capacity numbers:

ArrayList-10
Vector-10
HashSet-16
HashMap-16
HashTable-11
Copy after login

The initialization capacity of ArrayList is the same as that of Vector, which is 10; the initialization capacity of HashSet and HashMap Same, it is 16; and HashTable uses 11 alone, which is another very interesting question.

The above is the detailed content of What is the reason why the initial capacity of ArrayList in Java is 10?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles