0

for example:

for (int i = 0; i < 10; i++){
   SomeClass something = new SomeClass();
   something.setOnClickListener(new OnClickListener() {
      public void onClick(){
         doSomething(i);
      }
   });
}

I am not allowed to use the variable i, Eclipse suggest me make the i final, but I cannot do that because I need it to iterate right?

nomnom
  • 1,560
  • 5
  • 17
  • 31

2 Answers2

6

Copy i to a final variable in the loop body.

for (int i = 0; i < 10; i++){
   final int j = i;
   SomeClass something = new SomeClass();
   something.setOnClickListener(new OnClickListener() {
      public void onClick(){
         doSomething(j);
      }
   });
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

You can do

loop with i
  final int k = i
  annonymousClass
Lan
  • 1,206
  • 1
  • 11
  • 26