could we get easier conversion of arrays to iterables

Brian Goetz brian.goetz at oracle.com
Sun Jul 22 09:32:17 PDT 2012


There is already Arrays.asList().  (We may add additional convenience methods to Arrays to convert to additional new types, such as Arrays.asParallel()).  

What you are suggesting is a not-small language feature to provide a small bit of sugar to something you can already easily do with the libraries.  So, while we've considered the possibility of adding a mechanism for injecting methods into arrays, the ease of just wrapping the array in this manner suggests we are probably better off spending our complexity budget elsewhere, unless we can derive some other larger benefit from this.  

(In the "spend the complexity budget elsewhere" department,  just in the area of arrays, we've got lots of more serious problems that don't have a simple library-based solution: 32 bit size limitation, can't have final or volatile elements, array literals, better constant-pool support, etc.)  

On Jul 22, 2012, at 11:41 AM, 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
> 
> 



More information about the lambda-dev mailing list