New Collections interface - Sized

Brian Goetz brian.goetz at
Fri Apr 23 16:07:56 UTC 2021

This has come up before.  For example, during an early iteration of the 
Stream design, before parallelism entered the picture.  The first 
scrawled-on-a-napkin prototype for streams was based on Iterator, and it 
took about a minute to realize that we could do a much better job if we 
had a slightly broader interface to work with, essentially Iterator+Sized.

When you pull on this string, you end up with a lot of new interfaces, 
such as SizedIterator, SizedIterable, etc, in part because ... we have 
no intersection types.  Having lots of fine-grained interfaces for "has 
X" and "has Y" is nice from a "bucket of lego bricks" library-design 
perspective, but when the user goes to express "I need an aggregate that 
has sizes, iterators, and encounter order", you end up with code like:

     <T, X extends Iterable<T>&Sized> void foo(X x) { ... }

and then you run into the wall of "but I can only use intersection types 
in these places in the language."  The idiom of having fine-grained 
mix-in-ish interfaces really wants a language with intersection types.

Additionally, I am having a hard time imagining how Sized would be 
usable by a client; no method will *take* a Sized (it's just not broad 
enough), and I can't immediately imagine what would even *return* a 
Sized.  If the type is not suitable for use by clients, then it serves 
only to organize the library itself, and that's a weaker motivation.

Is there a compelling example of where this would be used by clients?

On 4/23/2021 5:23 AM, Stephen Colebourne wrote:
> Hi all,
> While a discussion on ReversibleCollection is going on, I'd like to
> raise the interface I've always found most missing from the framework
> - Sized
>   public interface Sized {
>     int size();
>     default boolean isEmpty() {
>       return size() == 0;
>     }
>     default boolean isNotEmpty() {
>       return !isEmpty();
>     }
> }
> This would be applied to Collection and Map, providing a missing
> unification. Anything else that has a size could also be retrofitted,
> such as String. Ideally arrays too, but that could come later. Note
> that Iterable would not implement it.
> Stephen

More information about the core-libs-dev mailing list