Cast Regular Int to Final Java [duplicate]

天涯浪子 提交于 2019-12-23 02:56:39

问题


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?


回答1:


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);});
}



回答2:


This is the idiom:

for(int i = 0; i < 10; i++)
{
  final int j = i;
  panels[i].printI(new printI(){System.out.println(j);});
}



回答3:


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]);});
}


来源:https://stackoverflow.com/questions/23157842/cast-regular-int-to-final-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!