could we get easier conversion of arrays to iterables

Rémi Forax forax at univ-mlv.fr
Sun Jul 22 09:34:04 PDT 2012


On 07/22/2012 05:41 PM, Arne Siegel wrote:
> Hallo,
>
> in Java SE 5 the enhanced for statement for iterating through collections was introduced,
> equally available for iterating through arrays:
>
> for (T t : <some iterable - normally a collection>) ...
>
> for (T t : <some array>) ...
>
>
> It seems inconsequential that this ease of using arrays similar to collections shall not be
> available more broadly with Java SE 8. I'd like to mention two possible JLS extensions.
>
>
> First solution: Adding asList() to the members of the array type, implemented with
> Arrays.asList(<array>). Examples:
>
> dir.listFiles().asList().forEach(file -> { file.delete(); });
>
> public void setFlags(Flags ... flags) {
>      this.flags = new HashSet<Flags>(flags.asList());
> }
>
>
> Second solution: Hiding the conversion completely. Examples:
>
> dir.listFiles().forEach(file -> { file.delete(); });
>
> public void setFlags(Flags ... flags) {
>      this.flags = new HashSet<Flags>(flags);
> }
>
>
>
> Pros&Cons of the second solution, compared to the first:
>
> Pro: more concise
>
> Pro: higher analogy to the enhanced for statement, which doesn't demand an extra ".asList()"
>
> Con: has a similarity to the auto-boxing conversion introduced in Java SE 5, so the
> corresponding auto-unboxing conversion would have to be discussed in conjunction, not
> promising a convincing result
>
> Con: the analogy to the enhanced foreach loop is not 100%, as the auto-conversion would
> need to be to List, not Iterable, for my second example to work (although it could be
> reformulated using <array>.into(...) )
>
>
>
> Don't forget that both solutions have a big Pro compared to the current situation:
> Con: better readability of source code.
>
>
> Sure, what I'm desiring is just some additional bit of syntactic sugar. How are the chances?
>
> Regards
> Arne Siegel
>
>

The main issue is that currently there is no 'real' method on an array type,
so usually VMs have a special way to represent them,
what you propose does require big changes from the VM point of view.

Rémi




More information about the lambda-dev mailing list