ReversibleCollection proposal

Stuart Marks stuart.marks at oracle.com
Fri Apr 23 06:33:21 UTC 2021



On 4/22/21 8:36 AM, Stephen Colebourne wrote:
> On Thu, 22 Apr 2021 at 13:58, Remi Forax <forax at univ-mlv.fr> wrote:
>> I would like to preserve the invariant that, when calling a method on a Collection/iterator, an UnsupportedOperationException only occurs when trying to mutate that collection.
>> If we are ok with that, this means that addFirst can not be a default method of Collection.
> 
> This implementation meets the invariant:
> 
>   public interface Collection<E> .... {
>     default void addFirst(E e) { add(e); }
>     default E getFirst() { return iterator().next(); }
>     default E removeFirst() {
>       var i = iterator(); i.next();
>       i.remove();
>     }
>   }
> 
> This is what I intended anyway, ie that its OK for "first" to work on
> an unordered collection, just that addFirst() has very weak semantics
> wrt first-ness.
> 
> "Ensures that this collection contains the specified element(optional
> operation). This has the same basic behaviour as add(E), but
> implementations may choose to add the element in first position if
> they have some kind of guarantee of ordering. An exception should not
> be thrown unless add(E) would also have thrown the exception."

What seems to be going on here is that people want to add generality by promoting 
this set of methods from ReversibleCollection up to Collection. Unfortunately, the 
only way to do so is to make the specification so loose that the semantics are 
destroyed.

Having these methods on Collection could lead to a situation where calling addFirst 
and then getFirst might result in getFirst returning a different element from what 
was passed to addFirst. This doesn't make any sense for methods that have "first" in 
the name.

It seems like there's some other use case that people have in mind, such as "get an 
arbitrary element from this collection". The obvious way to implement this is 
iterator().next() which gets the "first" element from the iteration and so people 
are latching onto the name "getFirst". But let's not confuse the "first" element in 
a semantic ordering with the "first" element returned by an iterator. They're distinct.

s'marks


More information about the core-libs-dev mailing list