Web / Apache Commons Collections Interview questions
How does PredicatedList enforce validation on add operations?
PredicatedList<E> decorates an existing List and intercepts every operation that would introduce a new element - add(), addAll(), set(), and even listIterator().add()/set() - running a supplied Predicate against the candidate element first.
Predicate<Integer> positive = n -> n != null && n > 0; List<Integer> balances = PredicatedList.predicatedList(new ArrayList<>(), positive); balances.add(50); // succeeds balances.add(-10); // throws IllegalArgumentException, list is untouched
If the predicate returns false, a IllegalArgumentException is thrown before the underlying list is modified, so a failed validation never leaves the list in a partially updated state - this fail-fast guarantee holds even for bulk operations like addAll(), since every candidate is checked prior to insertion.
Because the check is embedded in the list itself rather than in calling code, every code path that touches the list - now and in the future - automatically inherits the validation, closing off the common bug where one insertion path is validated but another one added later is accidentally skipped.
More Related questions...