当前位置:网站首页>Common ArrayList interview questions
Common ArrayList interview questions
2022-07-27 21:15:00 【The slag height of writing bug】
List of articles
- ArrayList
- The efficiency of array expansion
- Bottom layer and source code analysis
- Capacity expansion
- Add process
- There are parametric structures
- How to copy something ArrayList To another ArrayList In the middle ?
- Thread safety problem
- ArrayList Inserting or deleting elements must be better than LinkedList Slow down
- ArrayList Suitable for queues
- ArrayList And LinkedList Ergodic performance ⽐ How is it
- ArrayList often ⽤ Of ⽅ To sum up
ArrayList
1, It can even be stored null
2. Based on the array is to achieve array storage
3. Wireless range safety control , That is, the thread is not safe , It's basically the same as Vector , In the case of multithreading, it is not recommended ArrayList
The efficiency of array expansion
When there is a large amount of data to be added , If there is no participation , The capacity of the array is gradually increasing , Then it will trigger many expansion , Because the array copy will be used during capacity expansion , This process is very performance consuming , It can lead to ArrayList Decline in efficiency
// Here is the test when adding a lot of data ,ArrayList The problem of sharp performance degradation
public class AddManyElementProblem {
public static void main(String[] args) {
add1();
}
// If capacity is specified
public static void add1(){
// Create a collection object
List<String> list = new ArrayList<String>();
// Additive elements
list.add("hello");
list.add("PHP");
list.add("Java");
long startTime = System.currentTimeMillis();
// demand : You also need to add 10W Data
for (int i = 0; i < 100000; i++) {
// Optimize the rendering
// Be careful : This optimization method is only for specific scenarios , If you add a few elements 、 Unknown , It is not recommended to use
// 4.3 ArrayList Inserting or deleting elements must be better than LinkedList Slow down ?
// Delete... According to index
// Case study :ArrayList and LinkedList contrast
list.add(i+"");
}
long endTime = System.currentTimeMillis();
System.out.println(" No capacity specified : "+ (endTime - startTime));
// Specify a large enough capacity when creating a set
List<String> list1 = new ArrayList<String>(100000);
startTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
list1.add(i+"");
}
endTime = System.currentTimeMillis();
System.out.println(" Specified capacity : "+ (endTime - startTime));
}
}
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-t1Kgj232-1658498591138)(images.images/image-20220722213420918.png)]
Bottom layer and source code analysis
1. One was maintained Objec Array of ,transient Object[] elementData
2 When you create an object , If you use parameterless construction , Then the initial capacity is 0, At this time, the first addition needs to be expanded to 10, If the capacity needs to be expanded again 1.5 times
3. If you use a specified size constructor , Expansion is the same 1.5
Add method :
First, determine whether the index is reasonable , Then determine whether the capacity meets , The principle here is : In extreme cases , At this time, the capacity = length =size, Then the minimum length required at present is size+1, If size+1 Greater than the current length , It should be expanded . If you don't need to expand , Then you can assign directly
public void add(int index, E element) {
rangeCheckForAdd(index);// Check whether the index range is correct
ensureCapacityInternal(size + 1); // This is to determine whether the expansion is needed , The principle is : In extreme cases , At this time, the capacity = length =size, Then the minimum length required at present is size+1, If size+1 Greater than the current length , It should be expanded
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
modCount Record the number of changes ,minCapacity-elementData.length If greater than zero , It means that the current length is not enough to store
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BEIIKpXh-1658498591138)(images.images/image-20220601104236172.png)]
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);// The original array 1.5 times , But the first time was 0
if (newCapacity - minCapacity < 0)// If ,
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)// If it is greater than the maximum array limit
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
// The real expansion is here , Copy to the new array and set the new capacity
elementData = Arrays.copyOf(elementData, newCapacity);
}
Capacity expansion
The capacity of nonparametric structure when it is created is 0, for the first time add When will the capacity be expanded , Otherwise, his internal array is an empty array , Then every time the array is full , Add again , Will trigger the expansion mechanism , Capacity expansion 1.5 times
There are parametric structures , When creating, the capacity is the incoming value , After the array is full , Add again , Will trigger the expansion mechanism , Capacity expansion 1.5 times .
Be careful : The timing of capacity expansion is after the internal array is full , Again add To expand the capacity of
Add process
ensureCapacityInternal: Judge whether to expand capacity
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Here to judge whether to expand ,size+1 Represents the minimum capacity in extreme cases , Because in extreme cases , The current array is full , The minimum capacity required is size+1
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
3. determine minCapacity, If you use a parameterless construct , Then the initial capacity is 0, When it's first added , This will return to 10. There's another situation , It's a parametric structure , But the transmission value is less than DEFAULT_CAPACITY, And will return to DEFAULT_CAPACITY,10. The purpose of this is to prevent when the capacity is small , Adding elements will trigger multiple expansion . For example, if you pass 2, Then two elements are added , It's going to be expanded , And then at this point 2*1.5=3, Adding the fourth element also requires capacity expansion , Multiple capacity expansion will be triggered , Affect performance .
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
4. Determine the number of modifications , Check what you need now minCapacity And the length of the array , If you need to expand, expand again
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);// Every time 1.5 times
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;// Call this method for the first time , because oldCapacity by 0
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win: If you exceed the maximum capacity to enter here
// Before the newCapacity Copies to elementData
elementData = Arrays.copyOf(elementData, newCapacity);
}
There are parametric structures
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
How to copy something ArrayList To another ArrayList In the middle ?
Use clone() Method
Use ArrayList Construction method
Use addAll Method
Thread safety problem
Of course, it's not thread safe , The thread safe version of the array container is Vector. Vector Is very simple to implement , It's all about ⽅ Legitimacy plus synchronized Just a matter of . You can also avoid ⽤Vector,⽤Collections.synchronizedList hold ⼀ Ordinary ArrayList Package as ⼀ Thread safe version The array container of can also , The principle is the same as Vector yes ⼀ What kind of , It's for all ⽅ Can't cover ⼀ layer synchronized.
ArrayList Inserting or deleting elements must be better than LinkedList Slow down
result :
In case of large amount of data , because ArrayList The underlying array , LinkedList Bottom two way linked list .ArrayList When adding or deleting , Head forward , The lower the efficiency of adding and deleting , because ArrayList You need to copy the array when adding or deleting . and LinkedList When adding or deleting 、 Search efficiency is not very high , In particular, the object is in the middle of the linked list
So when inserting and deleting elements in the middle / Or random search , When the amount of data is large ,ArrayList It might be better than LinkedList fast .
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index;// Move the element at the index position back one space
elementData[index] = element;
size++;
}
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);// Copy data here , That is, cover the element behind the element to be deleted to the position of the deleted element
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
ArrayList Suitable for queues
Queues are generally FIFO Of , fifo , If you use ArrayList, Then you need to delete the header of the array , Tail add , And vice versa , But there will be an operation involving array copy , It costs a lot of performance
ArrayList And LinkedList Ergodic performance ⽐ How is it
On ergodicity ArrayList want ⽐LinkedList Much faster ,ArrayList Traverse most ⼤ The advantage of is memory continuity ,CPU Internal cache Structure will cache continuous memory ⽚ paragraph , Sure ⼤ Reduce the performance overhead of reading memory
ArrayList often ⽤ Of ⽅ To sum up
- boolean add(E e)
Add the specified element to the end of this list .
- void add(int index, E element)
Insert the specified element into ⼊ The specified location in this list
- boolean addAll(Collection c)
As specified collection The order of elements returned by the iterator of , Will be collection All the elements in are added to the end of this list .
- boolean addAll(int index, Collection c)
Start at the designated location , Will specify collection All the elements in ⼊ In this list .
- void clear()
Remove all elements from this list .
- Object clone()
Back here ArrayList A shallow copy of the instance .
- boolean contains(Object o)
If this list contains the specified elements , Then return to true.
- void ensureCapacity(int minCapacity)
If necessary, , Increase this ArrayList Capacity of the instance , To ensure it ⾄ Less can hold the most ⼩ The number of elements specified by the capacity parameter .
- E get(int index)
Returns the element at the specified location in this list .
- int indexOf(Object o)
Return to this list ⾸ The index of the specified element for the next occurrence , Or if the list does not contain elements , Then return to -1.
- boolean isEmpty()
If there are no elements in this list , Then return to true int lastIndexOf(Object o) Return to the last... In this list ⼀ The index of the specified element for the next occurrence , Or if the list does not contain an index , Then return to -1.
- E remove(int index)
Remove the element at the specified location in this list .
- boolean remove(Object o)
Remove from this list ⾸ The next occurrence of the specified element ( If there is ).
- protected void removeRange(int fromIndex, int toIndex)
Remove the index in the list fromIndex( Include ) and toIndex( barring ) Between all the elements .
- E set(int index, E element)
⽤ The specified element replaces the element at the specified position in this list . int size() Returns a list of elements in this .
- Object[] toArray()
In proper order ( From ⼀ In the end ⼀ Elements ) Returns an array containing all the elements in this list .
- T[] toArray(T[] a)
In proper order ( From ⼀ In the end ⼀ Elements ) Returns an array containing all the elements in this list ; Returns the operation of the array ⾏ The time type is Specify the operation of the array ⾏ Time type .
- void trimToSize()
Put this ArrayList The capacity of the instance is adjusted to the current ⼤⼩.
边栏推荐
- Verilog HDL中的reg型变量的理解
- API gateway introduction
- Automated testing - unittest framework
- js闭包知识
- Set up discuz forum and break the stolen database
- "Harvest" NFT: 200 yuan to buy pictures on Taobao, and 300000 yuan on the chain
- Tips for file upload to bypass WAF
- Typroa 拼写检查: 缺少对于 中文 的字典文件
- LeetCode每日一练 —— 链表中倒数第 k 个结点
- Codeforces 1706E 并查集 + 启发式合并 + ST 表
猜你喜欢

mysql 最大建议行数2000w,靠谱吗?

建筑云渲染的应用正在扩大,越来越多的行业急需可视化服务

PHP代码审计6—文件包含漏洞

PHP代码审计5—XSS漏洞

Face recognition 5.1- insightface face face detection model training practice notes

A review of component parsing (Second Edition)

如何让个性化推荐即刻触达?云原生数据库GaussDB(for Redis)来助力

【历史上的今天】7 月 27 日:模型检测先驱出生;微软收购 QDOS;第一张激光照排的中文报纸

One of IOU target tracking: IOU tracker

使用百度飞桨EasyDL实现电商UGC图片自动分类
随机推荐
[anti shake and throttling]
Differences among native objects, built-in objects, and host objects
R language uses LROC function of epidisplay package to visualize ROC curve of logistic regression model and output diagnostic table, visualize multiple ROC curves, and use legend function to add legen
What if the start button doesn't respond after the win11 system updates kb5014668?
Digital leading planning first, focusing on the construction of intelligent planning information platform and the exploration and practice of application projects
[R language] [1] beginners learn the grammar of R language and edit it with rstudio
Qt opengl 让物体在关照下动起来,形成动画
Automatic classification of e-commerce UGC pictures using Baidu PaddlePaddle easydl
R language uses dplyr package to connect two dataframe data (left join)
LeetCode-209-长度最小的子数组
Codeforces 1706e merge + heuristic merge + st table
Leetcode daily practice - 876. Intermediate node of linked list
NATAPP内网穿透工具外网访问个人项目
“收割”NFT:200元淘宝买图,上链卖30万元
Good driving, inexpensive, comfortable and safe! Experience BYD song Pro DM-I in depth
Natapp intranet penetration tool Internet access personal projects
Custom learning rate
Brief description of tenant and multi tenant concepts in cloud management platform
一种比读写锁更快的锁,还不赶紧认识一下
LeetCode每日一练 —— 206. 反转链表