← All topics

Collections

How List, Set and Map work inside and which one to pick when.

100 questions

Start ▶
Level:
1 When would you pick ArrayList over LinkedList, and the other way around? Almost always ArrayList: indexed access is O(1), the data sits densely in memory, and it is friendly to the CPU cache. LinkedList only makes sense when you constantly add and remove at the head of the list, and even then ArrayDeque is usually better. Junior 2 Collection and Collections: what is the difference between these two names? Collection is the common interface for List, Set and Queue. Collections is a utility class full of static helper methods: sort, reverse, unmodifiableList, emptyList and so on. Junior 3 How do List, Set and Map differ from each other? List is ordered, allows duplicates, and is accessed by index. Set holds unique elements. Map holds key-value pairs, and each key is unique. Junior 4 How does HashSet decide that two elements are "the same"? It first uses hashCode() to find the bucket the element belongs in, then compares it with the elements in that bucket using equals(). If both match, the new element is not added. Junior 5 Can you put a null key or a null value into a HashMap? Yes. HashMap accepts one null key and any number of null values. TreeMap (with natural ordering), ConcurrentHashMap and Map.of do not accept null. Junior 6 What is the difference between a plain array and an ArrayList? An array's length is fixed at creation, and it can store primitives directly. An ArrayList grows on its own and has convenient methods, but it only holds objects (Integer, not int). Junior 7 What happens if you remove an element from a list inside a for-each loop? Most of the time a ConcurrentModificationException is thrown: for-each uses a hidden iterator, and the list was modified behind its back. The right way is iterator.remove() or list.removeIf(...). Junior 8 What is the Comparable interface for? Comparable gives a class a "natural order": through the compareTo method an object compares itself with another one. After that, Collections.sort, TreeSet and TreeMap can sort it without an extra comparator. Junior 9 In what order does TreeSet keep its elements, and what does that cost? TreeSet always keeps elements sorted, either in natural order or by the Comparator you give it. It is backed by a red-black tree, so add, remove and contains are O(log n). Junior 10 How does LinkedHashMap differ from a regular HashMap? LinkedHashMap returns entries in insertion order, because it threads them together with an extra doubly linked list. HashMap gives no guarantee about iteration order. Junior 11 In Queue, what is the difference between offer/poll/peek and add/remove/element? Throws an exception / Returns a special value — Insert: add(e) / offer(e) → false; Take from the head: remove() / poll() → null; Look at the head: element() / peek() → null Junior 12 Why is ArrayDeque recommended instead of the Stack class? Stack is an old class that extends Vector: every method is synchronized, and the index methods inherited from Vector let you break the stack discipline. ArrayDeque is faster and gives you clean push/pop/peek through the Deque interface. Junior 13 How do the lists returned by List.of() and Arrays.asList() differ? List.of gives a fully immutable list and does not accept null. Arrays.asList is a fixed-size "view" over an array: set works, add/remove don't, and if the array changes, the list changes too. Junior 14 What is the most convenient and cheapest way to iterate over a Map? When you need both the key and the value, use entrySet() or forEach((k, v) -> ...). Walking over keySet() and calling get() for every key does an extra lookup. Junior 15 Why can't you write List<int>, and how does that affect performance? Generics only work with reference types, because after compilation the type parameter becomes Object. That is why you use List<Integer>, and every int is automatically boxed into an Integer. Junior 16 How long does ArrayList.contains() take, and how can you speed it up? contains scans the list from start to end using equals, so it is O(n). If you ask "is it there?" many times, moving the data into a HashSet brings it close to O(1). Junior 17 Is Vector still used today, and how does it differ from ArrayList? It is almost never used in new code. Vector is also array-based, but every method is synchronized and it doubles in size when full. ArrayList has no synchronization, grows by 1.5x, and is faster. Junior 18 How do Map's getOrDefault, putIfAbsent and merge simplify your code? They fold the "is the key there or not" check into a single call. getOrDefault returns a fallback for a missing key, putIfAbsent writes only into an empty slot, and merge combines the old and new value. Junior 19 How do you sort a list by several fields? I pass the first field to Comparator.comparing(...), add the next with thenComparing(...), and call list.sort(...). For reverse order there is reversed() or Comparator.reverseOrder(). Junior 20 What does this code print, and why? It prints [2]. list.remove(3) with an int argument calls remove(int index) and removes the 4 at index 3, while the calls made with Integer.valueOf(...) remove by value. Junior 21 What happens in a HashMap if a class overrides equals but you forget hashCode? Equal objects get different hashes and land in different buckets. As a result, get with a freshly created "equal" key returns null, and a HashSet ends up with duplicates. Strong Junior 22 What happens if an object used as a HashMap key is modified afterwards? The object stays in the bucket chosen by its old hash, while the new hash points somewhere else. So get and containsKey can't find it, but the entry stays in the map as if "lost". Strong Junior 23 Why does this code throw an exception? Arrays.asList returns a fixed-size list, which is a view over the array. When removeIf tries to remove an element, an UnsupportedOperationException is thrown. Strong Junior 24 Show the difference between Collections.unmodifiableList and List.copyOf with an example. unmodifiableList is a read-only wrapper over the original list: if the original changes, the wrapper sees the change. List.copyOf creates an independent immutable copy and does not accept null. Strong Junior 25 What do HashMap's initial capacity and load factor parameters control? Capacity is the initial length of the bucket array (16 by default), and load factor is how full the array may get before it grows (0.75 by default). When the number of elements exceeds capacity * loadFactor, the array doubles and every entry is redistributed. Strong Junior 26 What are the ways to safely remove elements while iterating over a list? Iterator.remove(), Collection.removeIf(...), or a plain for loop with a reverse index. In new code the cleanest option is removeIf, which shifts elements in a single pass in ArrayList. Strong Junior 27 Can a HashSet end up with 2 elements and a TreeSet with 1? Explain with BigDecimal. Yes. new BigDecimal("1.0") and new BigDecimal("1.00") are not equal by equals (the scale differs), but compareTo returns 0. HashSet relies on equals, and TreeSet relies on compareTo. Strong Junior 28 Why do the elements look unsorted when you println a PriorityQueue? PriorityQueue is a binary heap inside: only the smallest element is guaranteed to be at the head, and the rest are not fully sorted. toString and the iterator simply read the array in order. Strong Junior 29 What happens to the original list if you modify a list returned by subList? subList is not a copy but a view of a slice of the original list. What you write to it shows up in the original. And if the original is modified other than through the subList, every later access throws a ConcurrentModificationException. Strong Junior 30 What is the difference between Hashtable and HashMap, and why is Hashtable called obsolete? Hashtable / HashMap / ConcurrentHashMap — Thread-safe: yes, one shared lock / no / yes, at the bucket level; null key/value: no / yes / no; Iteration: also has Enumeration / fail-fast iterator / weakly consistent Strong Junior 31 What happens step by step inside HashMap when map.put(key, value) is called? The key's hashCode() is taken and its high bits are mixed into the low ones, then the bucket index is found with (n - 1) & hash. If the bucket is empty, a new node is placed there; otherwise equals is used to look for a matching key, and either the value is replaced or the node is appended to the end of the chain. Middle 32 What problem does converting HashMap buckets to trees in Java 8 solve? In a bucket with many collisions, lookup drops from O(n) to O(log n). When a chain grows past 8 elements and the table is at least 64 long, the linked list turns into a red-black tree (TreeNode); if it shrinks below 6, it goes back to a list. Middle 33 Which would you pick, ConcurrentHashMap or Collections.synchronizedMap, and why? Usually ConcurrentHashMap: reads are lock-free, writes block only one bucket, and it has atomic operations like computeIfAbsent and merge. synchronizedMap takes one shared lock on every call and needs a manual synchronized block for iteration. Middle 34 How does CopyOnWriteArrayList work, and where does it make sense to use it? On every write (add, set, remove) a full copy of the internal array is made, while reads work on the old array without a lock. So it is meant for lists that rarely change but are read a lot, such as listeners or a configuration list. Middle 35 How do you write a simple LRU cache using LinkedHashMap? You create the LinkedHashMap with accessOrder = true and override removeEldestEntry: when the size goes over the limit, the least recently used entry is removed automatically. In a multithreaded environment you need to wrap it or use a ready-made cache library. Middle 36 How have you used TreeMap methods like floorKey, ceilingEntry and subMap on a real problem? TreeMap is a NavigableMap, and it gives you "nearest smaller/larger key" and range queries in O(log n). It is very handy, for example, for finding a fee tier by amount or for pulling the entries in a time window. Middle 37 What traps are there when you use Collectors.toMap? If two keys turn out the same, an IllegalStateException: Duplicate key is thrown; if a value is null, you get an NPE. To avoid this, pass a merge function and, if needed, specify the map type explicitly. Middle 38 What is the difference between fail-fast and weakly consistent iterators? A fail-fast iterator (ArrayList, HashMap) throws a ConcurrentModificationException right away if it notices the underlying collection changed. A weakly consistent iterator (ConcurrentHashMap, ConcurrentLinkedQueue) throws no exception and may see only some of the changes made during iteration. Middle 39 When do you use EnumMap and EnumSet instead of a plain HashMap/HashSet? Whenever the key is an enum, almost always. EnumMap uses a plain array indexed by the enum's ordinal() inside, and EnumSet uses a bit vector: no hash computation, little memory, and iteration in the order the enum is declared. Middle 40 When you need a queue, why is ArrayDeque often the better choice over LinkedList? Both give you O(1) operations at both ends, but ArrayDeque works on a circular array: no separate node is created for each element, the data sits densely in memory, and there is less load on the GC. In benchmarks it usually comes out several times faster. Middle 41 How does the internal array of an ArrayList grow, and where does it show up on prod? An empty ArrayList gets an array of size 10 on the first add, and when it fills up it grows by about 1.5x (old + old >> 1) and is copied with Arrays.copyOf. On large lists, these copies and having two arrays in memory at the same time increase allocation and GC pressure. Strong Middle 42 How are entries redistributed when a HashMap resizes, and why is the table length always a power of 2? A power of 2 lets you compute the index quickly with (n - 1) & hash. When the table doubles on resize, each entry either stays at its index or moves to index + oldCapacity. This is decided by one new bit of the hash, so there is no need to recompute hashes. Strong Middle 43 What happens if you modify the same map inside ConcurrentHashMap.computeIfAbsent? The mapping function runs under the bucket lock. Writing to the same map from inside it often throws IllegalStateException: Recursive update on Java 9+, while on Java 8 a thread could hang forever in some cases. The function must be short, free of side effects, and must not touch the map. Strong Middle 44 How does WeakHashMap work, and when can't it stop a memory leak? WeakHashMap holds keys through weak references: if no strong reference to the key remains anywhere else, the GC collects it and the entry disappears from the map on the next access. But the value is held by a strong reference, so if the value references its own key, the entry never goes away. Strong Middle 45 When do you need an IdentityHashMap? When keys must be compared by ==, not equals: walking an object graph and checking "have I seen this exact object?", serialization, deep copy, proxies. It uses System.identityHashCode and open addressing (linear probing). Strong Middle 46 When does "Comparison method violates its general contract!" appear, and how do you track it down? When TimSort inside List.sort/Arrays.sort notices contradictory comparator results, it throws an IllegalArgumentException. Causes: a transitivity violation, a - b overflow, a field that changes during the sort, wrong null handling, or returning a random value. Strong Middle 47 For producer-consumer, which do you choose: ArrayBlockingQueue or LinkedBlockingQueue? ArrayBlockingQueue is always bounded, with a preallocated array and a single lock. LinkedBlockingQueue has separate locks for put and take, so producers and consumers collide less, but if it is created unbounded it can eat all your memory. Strong Middle 48 What is ConcurrentSkipListMap, and when do you pick it over ConcurrentHashMap? It is a sorted concurrent map based on a skip list that works without locks (using CAS): get/put are O(log n), and it has the NavigableMap methods ceilingKey, headMap and pollFirstEntry. If you need ordering or range queries in a multithreaded setting, you pick it instead of ConcurrentHashMap. Strong Middle 49 How do you tell that a HashMap is running much slower than expected, and how does hashCode quality affect that? If a profiler shows HashMap.getNode/putVal or equals taking a lot of time, the cause is often a badly distributed hashCode: keys pile up in a few buckets, and a lookup walks a chain or tree instead of being O(1). Measure the hash distribution and fix hashCode. Strong Middle 50 What problem did the SequencedCollection interface in Java 21 solve? There is now a common API for ordered collections: getFirst, getLast, addFirst, addLast, removeFirst, removeLast and reversed(). Before, getting the first or last element was done differently in List, Deque, LinkedHashSet and SortedSet. Strong Middle 51 Do HashMap's keySet(), values() and entrySet() return copies? What happens if you remove an element through them or call setValue? None of them is a copy; each is a live window onto the Map. If you call remove, removeIf or retainAll on them, the entry disappears from the Map too, and entry.setValue replaces the value in place. Only add doesn't work. Strong Middle 52 Which algorithm runs inside List.sort() and Arrays.sort(), are they stable, and what does that mean in practice? For objects it is TimSort, which is stable and very fast on partially sorted data. For primitive arrays it is Dual-Pivot Quicksort, which is not stable, but with primitives you can't tell. Because it is stable, you can rely on the order of equal elements. Strong Middle 53 Why does HashMap do h ^ (h >>> 16) instead of using the key's hashCode() directly? The bucket index is taken only from the low bits of the hash. XOR-ing the high 16 bits into the low ones keeps keys that differ only in their high bits from piling up in a single bucket. Strong Middle 54 How do equals and hashCode behave when you use a record with an array or List component as a HashMap key or HashSet element? A record compares each component with Objects.equals. For an array that means reference equality, so two records holding arrays with the same contents are not equal. A List component is compared by contents, but if the list is mutable, the key can get "lost" inside the Map. Strong Middle 55 What structure is inside TreeMap, and what happens if the comparator is inconsistent with equals or a null key shows up? TreeMap is a red-black tree: put, get and remove are O(log n), and the tree height does not exceed about 2·log n. Keys are compared only with compareTo/compare, so two keys for which the comparator returns 0 become one key, and with natural ordering a null key throws an NPE. Strong Middle 56 What is a Spliterator, and what should a collection you write yourself look like for parallel streams to work well on it? A Spliterator is the source of a stream: it hands out elements and splits the work into chunks with trySplit(). The speed of a parallel stream depends on how even and cheap the splitting is, and on characteristics such as SIZED and ORDERED. Strong Middle 57 When you need a Set in multithreaded code, what do you take: ConcurrentHashMap.newKeySet(), Collections.newSetFromMap, or something else? If you don't need ordering, ConcurrentHashMap.newKeySet(): lock-free reads and an atomic add that answers the question "was I the first to add it?". If you need ordering, ConcurrentSkipListSet; for a small set that rarely changes, CopyOnWriteArraySet. Strong Middle 58 What kind of locking does Java 8+ ConcurrentHashMap use for writes, and what happens during a resize? An element goes into an empty bucket with CAS, without a lock. In an occupied bucket, synchronized is taken only on the first node of that bucket. During a resize, several threads split the work, and buckets that have been moved are marked with a ForwardingNode. Strong Middle 59 What do ConcurrentHashMap's bulk methods like forEach, search and reduce give you, and how does the parallelismThreshold parameter work? Since Java 8, ConcurrentHashMap has methods that traverse the Map without locks and, if needed, in parallel. parallelismThreshold is an estimated element-count limit: if the Map is smaller, the work runs on one thread; if larger, it is split and run in ForkJoinPool.commonPool(). Strong Middle 60 What is the difference between writing equals with instanceof and with getClass(), and what does it lead to when subclasses end up in a HashSet? With instanceof, a subclass object can be equal to its parent, but if the subclass adds its own field, symmetry breaks. getClass() preserves symmetry, but subclasses such as Hibernate proxies end up not equal to their "original". The choice depends on the class hierarchy. Strong Middle 61 What is BitSet, and when do you use it instead of Set<Integer> or boolean[]? BitSet is a set of bits over a long[]: one bit for each non-negative integer. When the values are dense and bounded (ids, day numbers, ports), it takes hundreds of times less memory than a HashSet<Integer>, and set operations like and and or are very fast. Strong Middle 62 How does DelayQueue work, and what do you watch out for when using it for delayed tasks? DelayQueue is an unbounded BlockingQueue with a PriorityQueue inside: elements implement the Delayed interface, and take() returns only an element whose delay has expired. It is handy for retries, timeouts and TTL cleanup, but everything lives in memory and is lost on restart. Strong Middle 63 What do Collections.emptyList(), singletonList() and nCopies() return, and what mistakes come up with them? All three return an immutable, lightweight list: emptyList is a single shared instance, singletonList is an object with one field, and nCopies doesn't store the element n times, only one reference and a count. If you add to them you get an UnsupportedOperationException. Strong Middle 64 How do ArrayList.removeAll() and retainAll() work, and why do they get slow when you pass a big List as the argument? ArrayList.removeAll(c) calls c.contains(e) for each of its elements. If c is a List, each contains is O(m) and the total is O(n·m): with 100,000 × 100,000 that is billions of comparisons. If you turn the argument into a HashSet, the work drops to O(n). Strong Middle 65 What is the RandomAccess marker interface for, and how does code that walks a List by index slow down with a LinkedList? RandomAccess is an interface with no methods, a tag meaning "get(i) is fast". ArrayList implements it and LinkedList doesn't. JDK algorithms pick index-based or iterator-based access based on it, while an indexed for loop turns into O(n²) on a LinkedList. Strong Middle 66 Why does a cache based on SoftReference cause GC and latency problems on prod? Soft references are cleared only when the heap is under pressure. So such a cache keeps the heap permanently full, the GC does extra work for it, and the clearing happens all at once, at the worst possible time. A cache bounded by size and time gives a predictable result. Strong Middle 67 If you write your own Iterator or Iterable that reads pages from a DB, what traps can you fall into? The most common mistakes: hasNext() having side effects (if it is called twice, an element is lost), next() returning null at the end instead of throwing NoSuchElementException, an Iterable that turns out to be one-shot, and an opened resource (cursor, connection) that never gets closed. Strong Middle 68 If you print a HashMap with small Integer keys, the keys come out looking sorted. Why, and what happens if you rely on it? Integer.hashCode() is the number itself, and the bucket is chosen with hash & (n - 1). If the keys are smaller than the table size, each one lands in the bucket with its own number, and iteration goes in bucket order, so the result looks sorted. That is an accident: once the keys grow, the order breaks. Strong Middle 69 Can you keep a Map.Entry taken from entrySet() to use later? How does it differ from Map.entry() and AbstractMap.SimpleEntry? Better not to: in HashMap the entry is the internal node itself and changes when the Map changes, TreeMap.firstEntry() gives an immutable snapshot, and other Maps behave differently again. If you need a pair, create an independent object with Map.entry(k, v) or a record. Strong Middle 70 Is new ArrayList<>(x).equals(new LinkedList<>(x)) true? What about HashSet and TreeSet, or a List and a Set? What is the equals contract for collections? Lists are equal if they have the same elements in the same order, regardless of implementation. Sets are equal if they have the same elements (order doesn't matter), and Maps if they have the same pairs. But a List is never equal to a Set, and for queues there is no general rule. Strong Middle 71 A HashMap<Long, Long> with tens of millions of entries takes up a large part of the heap in your service. How do you analyze it and cut the memory? First I measure where the memory is going with a heap histogram or a dump: usually the bulk is Node objects and boxed Longs. Then moving to a primitive collection (fastutil, Eclipse Collections) or changing the data structure saves 4 to 6 times. Senior 72 What is a "hash flooding" attack on HashMap, and how do you defend against it in Java? The attacker sends thousands of keys that land in the same bucket (for example request parameters or JSON fields), and every insertion turns into a linear scan, tying up the CPU. Treeification in Java 8 brings this down to O(log n), but you still have to limit the input size. Senior 73 How reliable is the size() result of a ConcurrentHashMap for metrics or business decisions? While parallel writes are happening, size() is an approximate value: it adds up the counter cells without a lock and may not match any single moment. That is enough for a metric, but you can't build a decision like "did we go over the limit" on it. Senior 74 Choosing a queue for ThreadPoolExecutor: how do you decide between ArrayBlockingQueue, LinkedBlockingQueue and SynchronousQueue? The queue type determines how the pool itself behaves: an unbounded LinkedBlockingQueue effectively disables max pool size and can fill up memory, a SynchronousQueue accepts a task only if there is a free thread, and a bounded ArrayBlockingQueue gives you backpressure. Senior 75 How do you find and reduce excess allocation caused by collections on a hot path? First I use an allocation profile (async-profiler -e alloc or JFR) to see which place allocates the most bytes. The usual culprits in collections are boxing, repeated copies, resizes and short stream chains. I cut them down by giving initial sizes, copying once, and using primitive structures. Senior 76 When a class returns a collection to the outside, how do you choose between a copy, an unmodifiable view and a Stream? It is a trade-off between safety, speed and semantics: a copy is fully independent but allocates on every call; an unmodifiable view is cheap but "live"; a Stream suits one-time reading. With immutable internal state I usually take the copy once in the constructor. Senior 77 What is the difference between Stream.toList(), Collectors.toList() and Collectors.toUnmodifiableList(), and what can you break when migrating code? mutable / null element — collect(Collectors.toList()): yes (an ArrayList in practice) / allowed; stream.toList(): no / allowed; collect(Collectors.toUnmodifiableList()): no / NPE Senior 78 Your team built a cache with a plain static ConcurrentHashMap. What problems do you see and what do you propose? The main problems are unbounded growth (no eviction), stale data (no TTL), parallel loading for the same key (a stampede) and no metrics. I would propose a ready-made library like Caffeine, with a size limit, a TTL and statistics. Senior 79 How do you correctly compare ArrayList and LinkedList on iteration speed, and what does the result depend on? In theory both are O(n), but in practice ArrayList is several times faster: the data sits contiguously in memory, and the CPU cache and prefetching work well. To compare correctly you need JMH, and you have to account for JIT warmup and the GC. Senior 80 How do you approach writing a large collection to a DB or sending it to an external API in batches, and where is it easy to go wrong? I split the data into fixed-size chunks and send each one in a separate transaction or request. The main risks: subList windows being tied to the original list, loading everything into memory, one error rolling back the whole job, and duplicates on retry. Senior 81 In a large codebase worked on by several teams, how do you roll out the rule "public APIs return only immutable collections"? Writing the rule down in a document isn't enough: I reinforce it with static analysis (ArchUnit, Error Prone, Sonar rules), a shared helper library and a code review checklist. On old code I apply it gradually, starting with the riskiest modules. Staff 82 How do you keep a lookup table with several million entries, used on every request, in memory: a HashMap, a sorted array or off-heap? The decision depends on the number of entries, how often they change, the latency requirement and the GC budget. For data that doesn't change or rarely updates, primitive arrays plus an atomic swap of an immutable snapshot often give the best balance. Staff 83 Should the company codebase adopt a primitive collection library like fastutil or Eclipse Collections? How do you justify the decision? They cut memory and allocation sharply, but they bring a new dependency, a new API and a learning cost for teams. I would propose using them only at hot spots that a profile and benchmark have shown, hidden inside a module. Staff 84 When do persistent (structural sharing) collections (Vavr, PCollections) beat the JDK's List.copyOf approach? When you need a new version on every change and the collection is large: a persistent structure reuses most of the old version, so a "copy" is O(log n), not O(n). For small collections and rare changes, the JDK's plain copy is simpler and faster. Staff 85 When you move from a local HashMap to a distributed map like Hazelcast or Redis, what changes in the semantics, and what do you prepare teams for? In a distributed map, keys are compared by serialized bytes, not by equals/hashCode, the value you get is a copy, every operation is a network call, and partial failures can happen. If code was written as "it's just a Map", silent bugs appear. Staff 86 How do you choose an equals/hashCode strategy for JPA entities kept in a HashSet and compared across services? A hashCode based on the generated id changes after the entity is saved and breaks the HashSet. I choose a stable business key or a UUID created in the application; if that isn't possible, a constant per-class hashCode and equals by id. Staff 87 What data structures do you use to build a per-client "N requests in the last 60 seconds" rate limiter in memory? An exact sliding log needs a queue of timestamps per client, but it eats a lot of memory. In practice I choose a sliding window counter (counters for the previous and current window) or a token bucket, built inside a ConcurrentHashMap with eviction. Staff 88 If a few "hot" keys in a ConcurrentHashMap are slowing down the whole service, how do you detect it and fix it? All writes to one key queue up for a single bucket lock: the CPU is busy, but throughput doesn't grow. In a profile you see synchronized monitor waits. The fix: split the counter with LongAdder, shard the key, or accumulate writes through a local buffer. Staff 89 How do large collections affect the GC, and how do you manage that in a service with a 30 GB heap? Large arrays become humongous objects in G1, taking separate regions and causing fragmentation; millions of small nodes increase marking and copying time. I manage this by giving collections an initial size, reducing the object count, and, if needed, changing the GC (ZGC). Staff 90 After a JDK upgrade, the order of elements changed in tests and reports. What is the cause, and how do you protect against it in the future? The code relies on the iteration order of HashMap/HashSet or Set.of/Map.of. That order is not guaranteed, and it changes between JDK versions, and in the case of Set.of even on every JVM start. The protection: where you need order, express it with the type, and catch order dependence in tests on purpose. Staff 91 For high-throughput messaging between services, how do you choose between ConcurrentLinkedQueue, LinkedBlockingQueue, JCTools and the LMAX Disruptor? First I answer the questions "does it need to block, does it need a bound, how many producers and consumers are there". For ordinary cases the JDK queues are enough; if you need millions of messages per second and microsecond latency, JCTools' specialized queues or the Disruptor are chosen after measuring. Staff 92 For a leaderboard updated in real time, how do you keep the top 100 and a user's rank: TreeMap, skip list, heap or Redis ZSET? With a single instance and a small volume, a ConcurrentSkipListMap or a TreeMap under a lock is enough, but a "what is this user's rank" query is O(n) in JDK structures. With many instances, a million players and a rank query, a Redis sorted set (skip list + rank) is the natural choice. Staff 93 In internal libraries and service interfaces, which do you make the standard return type for methods: List, Collection, Iterable or Stream? The return type is a contract: it says what is being promised to the caller. I usually make List the standard (it has order and size and can be iterated many times), Stream only for lazy or very large data, and I almost never use Iterable. Staff 94 What architectural problems come up when producing and accepting large collections as JSON in a REST API? If the collection size isn't bounded, the response and the request are built fully in memory, and a single big request can fill the heap. On top of that, the collection that comes out of deserialization differs from what you expect (mutable or not, with nulls, ordering). The solution is pagination or streaming, limits on input, and explicit DTO types. Staff 95 On prod the heap slowly grows and ends in an OOM after a few days, and the suspicion is on collections. How do you run the investigation? First I confirm the growth is a real leak using the old gen level after a Full GC in the GC log, then I take two heap dumps some time apart and compare the dominator tree and the diff in MAT. The culprit is usually a Map in a static or singleton, a listener list, or a ThreadLocal. Staff 96 In a big migration from Java 8 to Java 21, which collection-related behavior changes do you check ahead of time? Code that relies on iteration order, the null and immutability rules of the new Set.of/Map.of/toList(), recursive modifications inside computeIfAbsent now throwing exceptions, and conflicts with the Sequenced Collections method names. I look for them with tests, static analysis and a canary deploy. Staff 97 In a multi-tenant SaaS, you need to bound the in-memory cache fairly for each tenant. How do you design it? In a single shared LRU, a big tenant squeezes out the small ones, and a strict separate cache per tenant wastes memory. I choose a hybrid: a cache bounded by total weight, with quotas and metrics per tenant. Staff 98 Is it safe to give a HashMap that is built once and then only read to several threads without synchronization? Under what conditions? Yes, if the map is safely published after it is fully built (a final field, volatile, a concurrent collection, or thread start) and nobody modifies it afterwards. If it is handed over by writing to a plain field, another thread may see a half-built state. Staff 99 For a monitoring service, what structure do you use to keep an in-memory time window of the last 5 minutes of metrics: a ring buffer, an ArrayDeque or a TreeMap? If events arrive almost in order and you only need aggregates (sum, average, percentile), a ring buffer over time buckets is the cheapest and most predictable solution. With late-arriving events and arbitrary range queries, a TreeMap/skip list, but it is considerably more expensive. Staff 100 When would you propose a Bloom filter instead of a HashSet to deduplicate billions of events, and what are its risks? When a full HashSet doesn't fit in memory and you can tolerate a small percentage of errors in a "present" answer. A Bloom filter takes a few bits per element, but gives false positives and can't remove an element, so it is usually used as a fast filter in front of an exact check. Staff