Detailed source code explanation of common methods of ArrayList
I believe that almost all students will be asked about the similarities and differences between ArrayList and LinkedList during written tests and interviews. Those who are slightly prepared are already familiar with these problems. The former is based on array implementation, and the latter is based on linked list implementation; the former's random method is fast, while deleting and inserting at specified positions is slow, while the latter's random access is slow, and deleting and inserting at specified positions is fast; Both are thread-unsafe; differences between lists vs arrays and more.
One of the big differences between lists and arrays is that arrays need to be sized during initialization and cannot be dynamically expanded, while lists can be dynamically expanded. ArrayList is implemented based on arrays, so how does it achieve dynamic expansion?
There are three ways to initialize ArrayList:
For the first default construction method, ArrayList does not initialize the capacity, but points the element data reference of the list to an empty array.
private transient Object[] elementData;private static final Object[] EMPTY_ELEMENTDATA = {};
//1.ArrayList默认构造方法public ArrayList() { super();this.elementData = EMPTY_ELEMENTDATA; }
Different from JDK1.6, JDK1.6 will initialize the capacity even when calling the default constructor. JDK1.7 Of course, it will bring certain benefits. If it is initialized and not used, the storage space will be wasted. Just wait until it is added and then initialize the capacity.
//JDK1.6 ArrayListpublic ArrayList() {this(10); }
For the second construction method, directly create an array of the specified size and point the element array reference of the list to it.
//2.ArrayList带有初始化大小的构造方法public ArrayList(int initialCapacity) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);this.elementData = new Object[initialCapacity]; }
The third construction method can pass a collection as a parameter, but the elements in the collection must inherit from the elements in the ArrayList.
//3.可将一个集合作为ArrayList的参数构造成ArrayListpublic ArrayList(Collection<? extends E> c) { elementData = c.toArray(); //将集合转换为数组size = elementData.length; //集合中的元素大小// c.toArray might (incorrectly) not return Object[] (see 6260652) 这里是个bug,参考http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6260652if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
A bug was mentioned above, which means that when converting a collection into an array, Object[] may not be returned by mistake. Here is an example.
1 package com.algorithm.sort; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.List; 6 7 /** 8 * bug编号:6260652。toArray有可能不会返回Object[] 9 * Created by yulinfeng on 2017/6/26.10 */11 public class Test {12 public static void main(String[] args) {13 correctly();14 incorrectly();15 }16 17 /**18 * 返回Object[]19 */20 private static void correctly() {21 List<String> list = new ArrayList<String>();22 list.add("test");23 System.out.println(list.getClass());24 Object[] objArray = list.toArray();25 System.out.println(objArray.getClass());26 }27 /**28 * 不返回Object[]29 */30 private static void incorrectly() {31 List<String> list = Arrays.asList("test");32 System.out.println(list.getClass());33 Object[] objArray = list.toArray();34 System.out.println(objArray.getClass());35 }36 }
Running result:
The above example illustrates that toArray does not always return Object[]. Object[], the Object element cannot be inserted, so the JDK fixed this bug in "6260652".
Next, let’s look at other methods such as element insertion and deletion.
//ArrayList#addpublic boolean add(E e) { ensureCapacityInternal(size + 1); //确保容量是否充足elementData[size++] = e; //将元素添加至数组return true; }
//ArrayList#ensureCapacityInternalprivate void ensureCapacityInternal(int minCapacity) {if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); //如果此时还没有初始化列表容量大小,则对其初始化,默认容量为10 } ensureExplicitCapacity(minCapacity); //检查容量是否充足}
//ArrayList#ensureEcplicitCapacityprivate void ensureExplicitCapacity(int minCapacity) { modCount++; //注意此变量if (minCapacity - elementData.length > 0) grow(minCapacity); //容量不够则进行扩容}
In the ensureEcplicitCapacity method, there is a modCount (modify count) variable that is incremented.
protected transient int modCount = 0;
This variable will not only increment in the add method, but will be recorded and incremented by 1 whenever there is a change to the ArrayList structure such as addition or deletion. The reason for this is the same as in multi-threading. Iterator is related to iterator traversal. There is also a variable corresponding to it in AbstractList$Itr.
//AbstractList$Itrint expectedModCount = modCount;
The checkForComodification method is called in AbstractList$Itr#next.
//AbstractList$Itr#checkForComodificationfinal void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException(); }
If the current running environment is single-threaded, no matter what operations are performed on the list, such as adding, modifying, deleting, etc., unexpectedModCount will always be equal to modCount, but if the current running environment is With multi-threading, it is very likely that one thread is iterating while another thread is adding or modifying it. JDK does not allow this. In this case, a ConcurrentModificationException will be thrown. This is where the modCount variable comes from. effect.
Return to the ArrayList#add method. When the list capacity is insufficient, the grow method will be called to expand the capacity.
//ArrayList#growprivate void grow(int minCapacity) {int oldCapacity = elementData.length;int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容策略为,每次新增容量的大小为旧容量的一半。也就是说如果默认容量为10,则第一次扩容大小为10 / 2 = 5,第二次扩容大小为15 / 2 = 7。if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //扩容策略扩得太小if (newCapacity - MAX_ARRAY_SIZE > 0) //扩容策略扩得太大,大于最大数组大小时,最多等于Integer.MAX_VALUEnewCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
ArrayList gets the element get method at the specified index position.
public E get(int index) { rangeCheck(index); //检查索引是否越界return elementData(index); }
Since ArrayList is implemented based on arrays, this method is relatively simple. Just judge whether it is out of bounds. If not, just index and return the elements according to the array subscript. The remove method deletes the element at the specified position.
//ArrayList#removepublic E remove(int index) { rangeCheck(index); //检查索引是否越界modCount++; //记录modCount,上面已提及E oldValue = elementData(index); //取出指定索引元素int numMoved = size - index - 1; //移动的元素个数if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; //将最后一个数组元素置为null,方便GCreturn oldValue; }
The code is relatively simple, and it also reflects the efficiency problem of ArrayList based on array practice when deleting specified elements. For information about the Arrays.copyOf and System.arraycopy methods, please refer to "The Difference between System.arraycopy(src, srcPos, dest, destPos, length) and Arrays.copyOf(original, newLength)"
The above is the detailed content of Detailed source code explanation of common methods of ArrayList. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual
