New Collections interface - Sized
Remi Forax
forax at univ-mlv.fr
Fri Apr 23 22:51:13 UTC 2021
----- Mail original -----
> De: "Stephen Colebourne" <scolebourne at joda.org>
> À: "core-libs-dev" <core-libs-dev at openjdk.java.net>
> Envoyé: Vendredi 23 Avril 2021 11:23:03
> Objet: New Collections interface - Sized
> 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.
>
> WDYT?
There are 3 ways to have instances of different classes to have a common behavior in Java,
- either thy implement a common super-type
- or you use a structural type conversion (a method ref on an instance)
here:
Sized sized = list::size;
- or you use pattern matching (or a cascade of if/else if you are like the old fashion)
int size(Object o) {
return switch(o) {
case List<?> list -> list.size();
case Object[] array -> array.length();
case String s -> s.length();
default -> throw ...
};
}
The advantage of pattern matching is that it does not have a global impact, out of where you want to use it,
by example, here, you can use s.length() instead of s.codepoints().count() without having to think what the default size of a String means for all program that can be written.
>
> Stephen
Rémi
More information about the core-libs-dev
mailing list