RFR: 8368178: Add specialization of SequencedCollection methods to emptyList, singletonList and nCopies [v2]

Stuart Marks smarks at openjdk.org
Mon Sep 22 17:02:50 UTC 2025


On Mon, 22 Sep 2025 08:06:55 GMT, Tagir F. Valeev <tvaleev at openjdk.org> wrote:

>> @amaembo `SequencedMap` already implements `Map`.  :-) So, we could say:
>> 
>> 
>> public static final <K,V> SequencedMap<K, V> emptyMap() { ... }
>> 
>> 
>> An empty map could also "incidentally" implement `SequencedMap`.
>
> @minborg as JLS 13.4.15 says,
>> Changing the result type of a method, or replacing a result type with void, or replacing void with a result type, has the combined effect of deleting the old method and adding a new method with the new result type or newly void result
> 
> Changing the result type from `Map` to `SequencedMap` will modify the binary signature, so compiled classes that used this method previously will fail with `NoSuchMethodError`. That's why simply changing `Map` to `SequencedMap` is not quite possible. My trick with `M extends Map<K, V> & SequencedMap<K, V>` employs the fact that the type parameter gets erased to its first bound, which is `Map`, so such kind of return type replacement is safe (but ugly).

@amaembo @pavelrappo 

Hm, a lot of issues to try to address. :-)

First, the initial proposal of adding overrides to EmptyList, SingletonList, and CopiesList is reasonable. No complications there.

On the serializablity of reversed views: in general, the view collections aren't serializable. This also includes things like subList, entrySet, and so forth. The design intent is mostly that they be used temporarily for iteration or copying, and typically aren't stored as the state of some other object. Now that doesn't prohibit a reversed view from being serializable. As Tagir noted, if a list is serializable, and `list.reversed().reversed()` returns the original list, the return value of reversed() will indeed be serializable. Notable exceptions are the views of TreeMap, which are serializable. Not sure why that was the case.

While the spec of the reversed() method is silent on serializability, List.copyOf()'s spec includes a bunch of requirements including serializability, so it pretty much needs to make a copy reversed views that aren't serializable.

Finally, I think you straightened it out, but as you noted, the `@implSpec` for List.reversed() specifies that calling reversed() on the reversed view returns the original list. This applies _only_ to the implementation of the reversed() method on the view returned by the default method, but it's not a requirement inherited by all implementers of the reversed() method. Most implementations indeed do this, but some don't -- like the aforementioned TreeMap.

-------------

PR Comment: https://git.openjdk.org/jdk/pull/27406#issuecomment-3320201402


More information about the core-libs-dev mailing list