Auto indexing improved for() loops
Remi Forax
forax at univ-mlv.fr
Sat Dec 9 08:33:37 UTC 2023
> From: "P Holder" <pholder at gmail.com>
> To: "amber-dev" <amber-dev at openjdk.org>
> Sent: Tuesday, December 5, 2023 10:00:50 AM
> Subject: Auto indexing improved for() loops
Hello,
> I'm participating in Advent of Code 2023 using Java.
So am i, but no loops only streams :). [1]
> It reminds me how I frequently wish I could have an index in a modern for loop
> without having to resort to using the old/traditional for loop. Now that the
> JEP 456 Unnamed Variables & Patterns is progressing nicely I can see how it
> could be used implicitly to grant my wish.
> Instead of writing:
> final String[] strings = getSomeStrings();
> int index = 0;
> for (final String str : strings)
> {
> // use the str and the index
> index++;
> }
> and risking the chance I may forget to place the index++ ... I would rather have
> something like:
> final String[] strings = getSomeStrings();
> for (int index, final String str : strings)
> {
> // use the str and the index
> }
> where the new part "int index" is optional, and the compiler could treat it like
> "int _" if not specified. Of course it could also be long, one assumes.
> I do realize it's merely syntactic sugar and I do know how to write the code I
> need, but it does surprise me the number of times I end up writing old for
> loops simply because I could use the index, but otherwise know doing it the
> modern way is cleaner and more expressive, if only I had the index too.
One advantage of the current design is that it makes the intent of the developer clear,
if it's a simple loop, use the enhanced for loop, if it's more complex, then use the classical C for loop
(both IntelliJ and Eclipse knows how to go back and forth).
By introducing an index in the design, you are muddying the water because now you can have loop that does side effect on the data structure you are looping on,
By example, I'm not sure i like the following code
List<String> list = ...
for(int index, String s : strings) {
strings.set(index, ...);
}
Also, looping with an index on a List is a kind of dangerous if you do not know the implementation of the List,
With the code above if 'strings' being a LinkedList<String>, the worst case complexity is O(n2). Again, not something we want people to write.
I think i would prefer to have to have an indexed stream more than indexed loop, the good news is that it seems something we can do using the gatherer API [2] and Valhalla (to avoid the cost of creating a a pair (index, element) for each element).
regards,
Rémi
[1] [ https://github.com/forax/advent-of-code-2023 | https://github.com/forax/advent-of-code-2023 ]
[2] [ https://openjdk.org/jeps/461 | https://openjdk.org/jeps/461 ]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231209/579904e6/attachment-0001.htm>
More information about the amber-dev
mailing list