Lists.transform: Preserve spliterator characteristics from backing list #8170
+32
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
spliterator()inTransformingSequentialListandTransformingRandomAccessListto delegate to the backing list's spliterator viaCollectSpliterators.map()IMMUTABLEandCONCURRENTfrom the backing listIMMUTABLEcharacteristic preservation withCopyOnWriteArrayListMotivation
When using
Lists.transform()with aCopyOnWriteArrayList, concurrent modifications cause spuriousConcurrentModificationException:Root cause:
CopyOnWriteArrayList.spliterator()has theIMMUTABLEcharacteristic, which tells the Stream API it's safe to iterate without CME concerns. However,Lists.transform()returns a list that inherits fromAbstractList, whose defaultspliterator()usesRandomAccessSpliterator- this does NOT preserve theIMMUTABLEcharacteristic, causing index-based iteration that throwsIndexOutOfBoundsException(converted to CME) when the list is modified.The fix: Override
spliterator()to useCollectSpliterators.map(), which preservesIMMUTABLE,CONCURRENT,ORDERED,SIZED, andSUBSIZEDcharacteristics from the backing spliterator. This matches the pattern already used inCollections2.TransformedCollection.Testing
ListsTesttests passtestTransformSpliteratorPreservesCharacteristics()verifiesIMMUTABLEis preservedCompatibility
This change only affects the spliterator behavior, not iteration via
Iterator. The spliterator will now correctly report characteristics inherited from the backing list, which is strictly more correct behavior.Fixes #8165
RELNOTES=
Lists.transform()now preserves spliterator characteristics (likeIMMUTABLE) from the backing list, preventing spuriousConcurrentModificationExceptionwhen wrapping concurrent lists.