Currently, I've been preparing for interview questions related to Java, and I find thread-safe Collections classes quite interesting. This is because I encountered a similar question related to Collections in a previous job interview. I would say that Collections is one of the most popular topics that interviewers like to ask about.
Thread-safe collections, such as the following examples, ensure safe concurrent access to data
ConcurrentHashMap
SynchronizedHashMap
Stack
Vector
CopyOnWriteArrayList
CopyOnWriteArraySet
HashTable
Add element in List while iterating
First of all, how to add element in List while iterating in java?
1 2 3 4 5 6 7 8 9 10
List<String> list = newArrayList<>(); list.add("a"); list.add("b"); list.add("c"); for(String s : newArrayList<>(list)) { if(s.equals("a")) { list.add("z"); } System.out.println(s); }
Above code will throw a ConcurrentModificationException which is used to fail-fast when we try to iterate and modify at the same time. So we can use the following substitue ways to do the smae thing.