Add a temporary final
variable to hold the value:
for(int i = 0; i < 10; i++)
{
final int tmp = i;
panels[i].printI(new printI(){System.out.println(tmp);});
}
Pergunta
I am trying to implement an inner class within a loop, and have come into an interesting situation. The internal class has methods, however, when I try and access the variable, Netbeans gives me a compiler error and tells me to make the int final.
As the int is a looping variable, it can not be final. I have tried creating new variables and equating them to the looping variable, but this still throws the same error.
Here is the basic syntax (in pseudo-code):
for(int i = 0; i < 10; i++)
{
panels[i].printI(new printI(){System.out.println(i);});
}
Any ideas?
Solução
Add a temporary final
variable to hold the value:
for(int i = 0; i < 10; i++)
{
final int tmp = i;
panels[i].printI(new printI(){System.out.println(tmp);});
}
Outras dicas
This is the idiom:
for(int i = 0; i < 10; i++)
{
final int j = i;
panels[i].printI(new printI(){System.out.println(j);});
}
Or use the array variant, which saves you one line of code ;)
for(final int[] i = {0}; i[0] < 10; i[0]++)
{
panels[i[0]].printI(new printI(){System.out.println(i[0]);});
}