Home Java javaTutorial List in java: A brief introduction to the ArrayList and LinkedList implementation interfaces

List in java: A brief introduction to the ArrayList and LinkedList implementation interfaces

Jul 26, 2018 pm 02:22 PM

ArrayList is implemented based on arrays. It is a dynamic array whose capacity can grow automatically, similar to dynamically applying for memory and dynamically growing memory in C language. LinkedList is implemented based on a two-way circular linked list (which can be easily seen from the source code). In addition to being operated as a linked list, it can also be used as a stack, queue and double-ended queue.

1. Introduction to List

2. ArrayList

Characteristics of ArrayList

ArrayList is based on array implementation and is a Dynamic array, its capacity can automatically grow, similar to dynamically applying for memory and dynamically growing memory in C language.

ArrayList is thread-unsafe, can only be used in a single-threaded environment, in a multi-threaded environment you can consider using the Collections.synchronizedList(List list) function to return A thread-safe ArrayList class, you can also use the CopyOnWriteArrayList class under the concurrent package.

ArrayList implements the Serializable interface, so it supports serialization, can be transmitted through serialization

ArrayList implements the RandomAccess interface, supporting fast random access, which is actuallyQuick access through subscript serial number

Implements the Cloneable interface, can be cloned

Pay attention to its three different construction methods. The capacity of the ArrayList constructed by the parameterless constructor is 10 by default. The constructor with Collection parameters converts the Collection into an array and assigns it to the ArrayList implementation array elementData. There is also a constructor that specifies the capacity.

Pay attention to the method of expanding capacity, ensureCapacity. Each time an element is added to ArrayList (it may be 1 or a group), this method must be called to ensure sufficient capacity. When the capacity is not enough to accommodate the current number of elements, the new capacity is set to 1.5 times the old capacity plus 1. If the set new capacity is not enough, the new capacity is directly set to the passed in parameter (that is, the required capacity), and then use the Arrays.copyof() method to copy the elements to a new array (see point 3 below for details). It can be seen from this that when the capacity is not enough, each time an element is added, the original elements must be copied to a new array, which is very time-consuming. Therefore, it is recommended to use ArrayList only when the number of elements can be determined in advance. , otherwise it is recommended to use LinkedList.

The implementation of ArrayList calls a large number of Arrays.copyof() and System.arraycopy() methods. It is necessary for us to have an in-depth understanding of the implementation of these two methods.

First look at the Arrays.copyof() method. It has many overloaded methods, but the implementation ideas are the same. Let’s look at the source code of the generic version:

public static <T> T[] copyOf(T[] original, int newLength) {
    return (T[]) copyOf(original, newLength, original.getClass());
}
Copy after login

Obviously another copyof method is called, which has three parameters, the last one The parameter specifies the type of data to be converted. The source code is as follows:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
    return copy;
}
Copy after login

It can be clearly seen that this method actually creates an array with a length of newlength inside it and calls System.arraycopy () method copies the elements in the original array to the new array.

Let’s look at the System.arraycopy() method. This method is marked native and calls the system's C/C code. It cannot be seen in JDK, but its source code can be seen in openJDK. This function actually ultimately calls the memmove() function of C language, so it can ensure the correct copying and moving of elements in the same array. It is much more efficient than the general copying method and is very suitable for batch processing of arrays. Java strongly recommends using this method when copying a large number of array elements to achieve higher efficiency.

Pay attention to the two toArray methods of ArrayList that are converted into static arrays.

The first one, Object[] toArray() method. This method may throw a java.lang.ClassCastException. If you directly use the downward conversion method to convert the entire ArrayList collection into an Array array of the specified type, this exception will be thrown. However, if you do not convert it into an Array array, Downcasting, but downcasting each element, will not throw this exception. Obviously, downcasting the elements in the array one by one is not efficient and inconvenient.

Second, T[] toArray(T[] a) method. This method can directly transform the Array converted from ArrayList downward as a whole (the transformation is actually implemented in the source code of this method), and it can be seen from the source code of this method that when the size of parameter a is insufficient, it will be called internally Arrays.copyOf method, this method internally creates a new array and returns it, so the common form of this method is as follows:

public static Integer[] vectorToArray2(ArrayList<Integer> v) {  
    Integer[] newText = (Integer[])v.toArray(new Integer[0]);  
    return newText;  
}
Copy after login

ArrayList基于数组实现,可以通过下标索引直接查找到指定位置的元素,因此查找效率高,但每次插入或删除元素,就要大量地移动元素,插入删除元素的效率低。

在查找给定元素索引值等的方法中,源码都将该元素的值分为null和不为null两种情况处理,ArrayList中允许元素为null

三、LinkedList

LinkedList的特点

LinkedList是基于双向循环链表(从源码中可以很容易看出)实现的,除了可以当做链表来操作外,它还可以当做队列双端队列来使用;

LinkedList同样是非线程安全的,只在单线程下适合使用;

LinkedList实现了Serializable接口,因此它支持序列化,能够通过序列化传输;

实现了Cloneable接口,能被克隆;

相关推荐:

接口测试基础之入门篇

视频教程:

去除ArrayList集合中的重复自定义对象元素案例

The above is the detailed content of List in java: A brief introduction to the ArrayList and LinkedList implementation interfaces. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1666
14
PHP Tutorial
1271
29
C# Tutorial
1251
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles