The non-deterministic iteration order of Immutable Collections

Remi Forax forax at univ-mlv.fr
Sun Mar 26 11:41:01 UTC 2023


----- Original Message -----
> From: "Jens Lideström" <jens at lidestrom.se>
> To: "core-libs-dev" <core-libs-dev at openjdk.org>
> Sent: Sunday, March 26, 2023 11:38:07 AM
> Subject: Re: The non-deterministic iteration order of Immutable Collections

> I think Map#of and friends would be more useful and less error prone if they
> where to return collections that have a fixed iteration order, where the order
> is defined by the insertion order when the map is created.

I agree.

They are several use cases for Set.of()/Map.of(), for testing you want them to not have an order but for a defensive copy (Set.copyOf()/Map.copyOf()) you want them to keep the order. Currently, the implementation rotates toward the former instead of the later.

A lot of my students struggle with the semantics of Set.of()/Map.of() because this choice makes the unmodifiable set/map not beginners friendly.
To the point where a student will prefer to use a List instead of a Set, because List.copyOf() seems to work "correctly" compared to Set.copyOf().

Python 3.7 has changed the implementation of its set and dictionaries to keep the insertion order for this exact reason.

Java could do the same.

regards,
Rémi


More information about the core-libs-dev mailing list