当前位置:网站首页>Iterator details in list... Interview pits
Iterator details in list... Interview pits
2022-07-05 12:36:00 【Hua Li Hu Shao】
List Small details of middle iterator
Hello everyone I'm handsome Li ! Kim San Yin four As a programmer who doesn't know the greatness of the world Of course, we should seize this opportunity to be severely beaten by society
Look at the problem first Deepen by the problem 、
// What happens to the following code
List list = new XXXList();
for(Object item: list){
list.remove(item);
}
This problem may often be seen, hahaha Very classic however ! It's very detailed There are many things involved
First see foreach grammar for(T item: list){} This is a Grammatical sugar Bottom In fact, it is traversed by the iterator That is to say Iterator
This syntax is compiled class The file looks like this
Execute the above code See what it looks like Is it the same as you think ( In the imagination Very different Everything is different from later ~)
And then we Change it this time
Delete this Will report ConcurrentModificationException Error of
Why is that? I'm not sure First We can see where the error was reported
Go straight into Iterator next The first line of the method This method of
If modCount != expectModCount It will make this mistake .
The problem is coming.
modCount and expectModCount What is it? ?
1, modCount
Actual number of modifications
be located AbstractList abstract class (ps: English is a good thing ! )
It involves rapid failure and Failure safety What?
then When the implementation class wants to use When you fail quickly
If in In the process of iterator iteration modCount change Then it will cause the above exception :**ConcurrentModificationException**
nudges
When This value will change ?
In execution ArrayList Of add Or is it remove Method time Will trigger the modification of this value
Na Simple and crude
2, expectModCount
Expected number of revisions
This is arrayList There is an attribute of iterator
He will assign values when the iterator is initialized This is to put modCount Given to He
When will he revise it ( Don't bother to take screenshots = =)
iterator remove Or is it add() When Note that it's an iterator
in other words After the iterator is initialized
You call next Method If you call list Class add perhaps remove Methods lead to modCount The value of has changed and expectModCount The values are different
Will throw ConcurrentModificationException
ok Now let's discuss why the above situation occurs
First look at the first column
This is normally executed and no error will be reported
Step by step
The first that hasNext Post it ··
cursor What is it? It is an attribute in the iterator Index of the next element
size That is, the size of the set
Notice that he directly uses it here, which is not equal to making judgments
teaList There is 2 Elements Corresponding subscript 0 Young people 1 Don't talk about military morality
First entry while Judge hasNext
The index of the next element is 0 size =2 Determine the successful entry stay next Determine whether the number of modifications is equal to the expected number of modifications Because it is not done after the iterator is created Add and delete operations therefore
This is the time The number of modifications is the same as the expected number of modifications Normal execution Take out item = Young people if Judge success call list Of remove Method Delete the “ Young people ” Be careful : Delete without iterators
This is the time size It becomes 1 Keep going down
Enter for the second time while hashNext The judgement of
The index of the next element is 1 however size Turned into 1 therefore Judgment failed It will jump out directly It won't come to next It will not determine the number of modifications So there's no mistake
( Two Or two or more sizes Delete the penultimate You can't report an error )
ok Here is the second example
This direct lv That's it
First entry while Judge hasNext No problem The normal process is executed downward
Enter for the second time while Judge hasNext The next element subscript is 1 size yes 2 Determine the success and enter the following logic
stay next Determine whether the number of modifications is equal to the expected number of modifications Because it is not done after the iterator is created Add and delete operations therefore
This is the time The number of modifications is the same as the expected number of modifications Normal execution Take out item = Don't talk about military morality if Judge success call list Of remove Method Delete ....
Then go to the next determine At this time, the subscript of the next element is 2 however size yes 1 At this time, it will still be judged to be successful Get into next Method because He did list Of remove
therefore The expected number of modifications is less than the actual number of modifications So at this point Will directly throw this error .ok 了
Finished ! Actually, it's OK Get to know What is security failure And fast failure . I don't have much here bb 了 People are interested in You can find out for yourself “ The more you know The more you don't know ” Here is forced to develop chic Li See you next time .
边栏推荐
- Take you hand in hand to develop a service monitoring component
- MySQL function
- July Huaqing learning-1
- Why learn harmonyos and how to get started quickly?
- GPS数据格式转换[通俗易懂]
- POJ-2499 Binary Tree
- Just a coincidence? The mysterious technology of apple ios16 is actually the same as that of Chinese enterprises five years ago!
- Clear neo4j database data
- GNN(pytorch-geometric)
- 嵌入式软件架构设计-消息交互
猜你喜欢
The evolution of mobile cross platform technology
UNIX socket advanced learning diary -ipv4-ipv6 interoperability
Four operations and derivative operations of MATLAB polynomials
Take you two minutes to quickly master the route and navigation of flutter
Pytoch monolayer bidirectional_ LSTM implements MNIST and fashionmnist data classification
Redis highly available sentinel cluster
Embedded software architecture design - message interaction
How can beginners learn flutter efficiently?
Detailed steps for upgrading window mysql5.5 to 5.7.36
Storage Basics
随机推荐
Reinforcement learning - learning notes 3 | strategic learning
UNIX socket advanced learning diary -ipv4-ipv6 interoperability
一款新型的智能家居WiFi选择方案——SimpleWiFi在无线智能家居中的应用
Solve the problem of cache and database double write data consistency
Handwriting blocking queue: condition + lock
MySQL regular expression
Pytoch counts the number of the same elements in the tensor
How can beginners learn flutter efficiently?
MySQL multi table operation
Learn the memory management of JVM 03 - Method area and meta space of JVM
Understand kotlin from the perspective of an architect
Correct opening method of redis distributed lock
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
GPS data format conversion [easy to understand]
只是巧合?苹果 iOS16 的神秘技术竟然与中国企业 5 年前产品一致!
Distributed solution - Comprehensive decryption of distributed task scheduling platform - xxljob scheduling center cluster
Semantic segmentation experiment: UNET network /msrc2 dataset
MySQL log module of InnoDB engine
Matlab struct function (structure array)