JDK-8165389 : adjust special-purpose collections to throw UOE unconditionally on calls to mutators
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • Submitted: 2016-09-02
  • Updated: 2016-09-06
  • Resolved: 2016-09-02
Related Reports
Relates :  
Description
The special-purpose collections, such as those returned by Collections.empty*, singleton*, nCopies, etc., are not consistent in the way they handle calls to mutator methods.

Unlike the unmodifiable wrappers (JDK-8165385) and the immutable collections produced by the convenience factories (JDK-8159404), these specialized collections often will not throw UnsupportedOperationException if a mutator is called in such a way as to be a no-op. For example,

    Collections.emptyList().addAll(Collections.emptyList())

will return normally and not throw any exception. This is in contrast to unmodifiable wrappers, where

    Collections.unmodifiableList(Collections.emptyList()).addAll(Collections.emptyList())

**will** throw UOE.

The behavior of the different specialized collections is not uniform. There are many cases where no exceptions are thrown when no-op mutators are called, but they aren't wholly consistent.

The questions are whether these various specialized lists should be brought into consistency with the unmodifiable wrappers and the immutable collections, and whether their specifications should require this behavior.
Comments
I would say "no" to both questions. The specialized collections have been this way for a very long time, so it would be an incompatible behavior change to make them throw UOE unconditionally. Doing this would probably prevent a certain number of programming errors, but I think that benefit would be outweighed by the cost of fixing code that would be broken by this change. If the behavior isn't changing, then the specification shouldn't change either. I'm filing this bug and closing it immediately as Won't Fix so that this issue and the rationale for this decision can be documented. Of course, if there is a compelling reason to proceed with this, it can always be reopened.
02-09-2016