Java lambda - for loop counter is not effectively final

后端 未结 4 1893
感情败类
感情败类 2021-01-19 00:18

Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 00:45

    You have to remember that a for loop actually equivalent to :

    int i=0;
    while(i < x.getBooks().size()){
      //execute your block
      i++;
    }
    

    So you see that i is declared only once and updated therefore not effectively final.

    It's a little unclear the relationship between x.getBooks() and Book.getAuthors() but apparently they have the same size? Without a better understanding, I don't think I can show you a better way to do it. But this might also show you that your design is poor.

提交回复
热议问题