sixtytrees sixtytrees - 6 months ago 11
Java Question

Using an array instead of int to deal with "potentially final variable" in Java.

Here is a sample of a code that uses an array

instead of an
. All lines containing
are shown in the the code below. This method is executed by several threads.

int[] i = {0}; //So the stream forEach doesn't complain about a potentially final variable to use...
result.forEach (currentOptionRow -> {
String bgColor = (0 == i[0] % 2) ? "eaeaea" : "ffffff";

//Create HTML, use bgColor to generate alternating background

Is this a workaround to get a mutable counter?
Why is it "potentially final"? (There is no
keyword, why is it a concern?)


This is a workaround necessary to deal with lambda requirements. Local variables for lambdas must be final or effectively final.

No, you can't replace it with int if you want to use lambda.

You can change values of elements stored in afinal int[]. That is why you can use it inside of lambda as a counter.