search
HomeJavajavaTutorialDetailed analysis of Java collection framework ArrayList source code (picture)

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;
}

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];//注意类型转换
}

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);//扩展空间并复制
}

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(Collection extends<a href="//m.sbmmt.com/wiki/166.html" target="_blank"> E> c)</a> method, one is the addAll(int index, Collection extends E> 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;
}

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
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version