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

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

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

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

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
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
Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

How do Java's Top Features Impact Performance and Scalability?How do Java's Top Features Impact Performance and Scalability?May 12, 2025 am 12:08 AM

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

JVM Internals: Diving Deep into the Java Virtual MachineJVM Internals: Diving Deep into the Java Virtual MachineMay 12, 2025 am 12:07 AM

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

What are the features that make Java safe and secure?What are the features that make Java safe and secure?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Must-Know Java Features: Enhance Your Coding SkillsMust-Know Java Features: Enhance Your Coding SkillsMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

JVM the most complete guideJVM the most complete guideMay 11, 2025 am 12:06 AM

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft