Collections.emptyList().sort() does nothing
Martin Buchholz
martinrb at google.com
Wed Nov 15 04:10:06 UTC 2017
Different maintainers of the core library differed on whether it's
important to pedantically check for such corner case mistakes. Recently
the trend has been to check for all errors up front, even if it ends up
making no difference. Users should not depend on the library implementer's
mood or vigilance, unless they're professional testers.
On Tue, Nov 14, 2017 at 7:52 PM, Tagir Valeev <amaembo at gmail.com> wrote:
> Hello!
>
> According to `List.sort` specification [1] "This list must be modifiable".
> According to `Collections.emptyList` specification [2] "Returns an
> empty list (immutable)."
>
> So I assume that `List.sort` cannot be called on
> `Collections.emptyList` result. However in fact this call is allowed
> doing nothing. Is this behavior documented somehow? Can I rely that it
> will not change in future Java updates?
>
> It's even more strange with `Collections.singletonList` [3] which
> "Returns an immutable list containing only the specified object".
> Obviously I cannot do:
>
> List<String> list = Collections.singletonList("foo");
> ListIterator<String> it = list.listIterator();
> it.next();
> it.set("bar"); // UOE
>
> However list.sort(null) works perfectly. On the other hand [1] clearly
> says:
>
> Throws: UnsupportedOperationException - if the list's list-iterator
> does not support the set operation.
>
> To me it seems that emptyList and (especially) singletonList
> implementation does not follow the specification. Am I missing
> something?
>
> With best regards,
> Tagir Valeev.
>
> [1] https://docs.oracle.com/javase/9/docs/api/java/util/
> List.html#sort-java.util.Comparator-
> [2] https://docs.oracle.com/javase/9/docs/api/java/util/
> Collections.html#emptyList--
> [3] https://docs.oracle.com/javase/9/docs/api/java/util/Collections.html#
> singletonList-T-
>
More information about the core-libs-dev
mailing list