Collections.emptyList().sort() does nothing

Andrej Golovnin andrej.golovnin at
Wed Nov 15 10:03:14 UTC 2017

Hi Bernd,

On Wed, Nov 15, 2017 at 7:04 AM, Bernd Eckenfels <ecki at> wrote:
> I would however vote for allowing an empty list to be sorted. This is such a common case to return a replacement empty list that it will not only introduce changed behavior but also forces ugly code.

I think we would need to write ugly code in any case as Java 9 has now
two empty list implementations: Collections.emptyList() and List.of().

Collections.emptyList().sort() does not throw an exception.

List.of().sort() throws an exception.

Best regards,
Andrej Golovnin

> For singleton list I can kind of understand that you want to fail early, but it could be made the same argument as for the empty case.
> In the end, if we allow one or both, it requires to be spelled out explicitely (unfortunately a spec change, even when it is the more likely usage already)
> Gruss
> Bernd
> --
> ________________________________
> From: core-libs-dev <core-libs-dev-bounces at> on behalf of Martin Buchholz <martinrb at>
> Sent: Wednesday, November 15, 2017 5:10:06 AM
> To: Tagir Valeev
> Cc: core-libs-dev
> Subject: Re: Collections.emptyList().sort() does nothing
> 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> 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.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]
>> List.html#sort-java.util.Comparator-
>> [2]
>> Collections.html#emptyList--
>> [3]
>> singletonList-T-

More information about the core-libs-dev mailing list