could we get easier conversion of arrays to iterables
Arne Siegel
v.a.ammodytes at googlemail.com
Sun Jul 22 08:41:05 PDT 2012
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