Table of Contents
Overall introduction
Method analysis
set()
get()
Home Java javaTutorial Detailed analysis of Java collection framework ArrayList source code (picture)

Detailed analysis of Java collection framework ArrayList source code (picture)

Mar 28, 2017 am 10:55 AM

Overall introduction

ArrayList implements the List interface, which is a sequential container where elements are stored The data is in the same order as it is put in. null elements are allowed to be put in. The bottom layer implements through the array. Except that this class does not implement synchronization, the rest is roughly the same as Vector. Each ArrayList has a capacity (capacity), which represents the actual size of the underlying array. The number of elements stored in the container cannot exceed the current capacity. When elements are added to the container, the container automatically increases the size of the underlying array if there is insufficient capacity. As mentioned before, Java generics are just syntax sugar provided by the compiler, so the array here is an Object array to be able to accommodate any type of object.

Detailed analysis of Java collection framework ArrayList source code (picture)

size(), isEmpty(), get(), and set() methods can all be completed in constant time. The time cost of the add() method is related to the insertion position. , the time cost of the addAll() method is proportional to the number of elements added. Most of the other methods are linear time.

In order to pursue efficiency, ArrayList is not synchronized. If concurrent access by multiple threads is required, users can synchronize manually or use Vector instead.

Method analysis

set()

Since the bottom layer is an arrayArrayListset()method also becomes It's very simple, just assign a value directly to the specified position in the array.

public E set(int index, E element) {
    rangeCheck(index);//下标越界检查
    E oldValue = elementData(index);
    elementData[index] = element;//赋值到指定位置,复制的仅仅是引用
    return oldValue;
}
Copy after login

get()

get()The method is also very simple. The only thing to note is that since the underlying array is Object[], you need to ## after getting the elements. #Type conversion.

public E get(int index) {
    rangeCheck(index);
    return (E) elementData[index];//注意类型转换
}
Copy after login

add()

is different from C++’s

vector, ArrayList does not have a bush_back() method, the corresponding method It is add(E e), ArrayList does not have the insert() method, the corresponding method is add(int index, E e). Both methods add new elements to the container, which may result in insufficient capacity. Therefore, before adding elements, the remaining space needs to be checked and automatically expanded if necessary. The expansion operation is finally completed through the grow() method.

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);//原来的3倍
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);//扩展空间并复制
}
Copy after login

Since Java GC automatically manages memory, there is no need to consider the issue of source array release here.

Detailed analysis of Java collection framework ArrayList source code (picture)

After the space problem is solved, the insertion process becomes very simple.

Detailed analysis of Java collection framework ArrayList source code (picture)

add(int index, E e)You need to move the element first, and then complete the insertion operation, which means that this method has a linear time complexity.

addAll()

addAll()The method can add multiple elements at one time. There are two handles depending on the position, one is added at the end addAll(Collectionextends<a href="http://www.php.cn/wiki/166.html" target="_blank"> E> c)</a> method, one is the addAll(int index, Collection c) method that inserts from the specified position. Similar to the add() method, space check is also required before inserting, and the capacity will be automatically expanded if necessary; if inserted from a specified position, elements may also be moved. The time complexity of
addAll() is not only related to the number of inserted elements, but also to the insertion position.

remove()

remove()The method also has two versions, one is remove(int index)Deletes the element at the specified position, and the other One is remove(Object o)Remove the first element that satisfies o.equals(elementData[index]). The deletion operation is the reverse process of the add() operation, which requires moving the element after the deletion point forward one position. It should be noted that in order for GC to work, the last position must be explicitly assigned a null value.

public E remove(int index) {
    rangeCheck(index);
    modCount++;
    E oldValue = elementData(index);
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    elementData[--size] = null; //清除该位置的引用,让GC起作用
    return oldValue;
}
Copy after login

The above is the detailed content of Detailed analysis of Java collection framework ArrayList source code (picture). 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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
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