On Thu, 22 Apr 2021 at 13:58, Remi Forax <fo...@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."

Stephen

Reply via email to