Hi to everyone. Sorry if this question has been asked before...
Is something like the code below legal? if yes, which are the
implications of making the variable i final?
for(final int i = 0; i < something; ++i) {
new AnonymousInnerClass() {
public void doSomething() {
...use i in some very creative way...
}
};
}
This code appears to work for me, but actually I would have expected
it to be in error since the loop might assign a new value to i on each
iteration, and the final keyword should forbid that. Am I missing
something? Will this code eventually make the computer explode? :)
Thanks for any insight on this...
cheers
Alessio Stalla
Lew - 17 Oct 2007 16:11 GMT
> Hi to everyone. Sorry if this question has been asked before...
> Is something like the code below legal? if yes, which are the
[quoted text clipped - 12 lines]
> iteration, and the final keyword should forbid that. Am I missing
> something? Will this code eventually make the computer explode? :)
There are special rules for for() loops. Give them a go; maybe you'll find it
easier to parse what they're saying than I do:
<http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html#16.2.12>
<http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html#16.2.4>
as they pertain to
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.4>

Signature
Lew
Christian - 17 Oct 2007 16:11 GMT
Alessio schrieb:
> Hi to everyone. Sorry if this question has been asked before...
> Is something like the code below legal? if yes, which are the
[quoted text clipped - 17 lines]
> cheers
> Alessio Stalla
you may not assign a new value within the loop to i if i is final
Alessio - 17 Oct 2007 16:16 GMT
never mind. Indeed it does not work, as I suspected.