Course contentsShow
← Java
Lesson 1724 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

Workarounds: Using Arrays and Wrappers

Explore techniques like single-element arrays or mutable wrappers to simulate mutable captured variables.

Workarounds: Using Arrays and Wrappers

What you'll learn: How to work around the effectively final restriction in lambdas by using single-element arrays or mutable wrapper objects.

Since lambdas cannot modify captured local variables (they must be effectively final), you sometimes need a workaround when you genuinely need to update a value from within a lambda. Two common techniques accomplish this: single-element arrays and mutable wrapper classes.

Why These Workarounds Work

The effectively final rule applies to the variable reference itself, not the contents of the object it points to. An array reference or wrapper object reference can remain effectively final while the contents inside change.

Single-Element Arrays

Create an array with one slot. The array reference never changes (effectively final), but you can modify the element inside:

int[] counter = new int[1]; // Reference stays the same
counter[0] = 0; // Initial value

list.forEach(item -> {
    counter[0]++; // Modifying array contents, not the reference
});

System.out.println("Count: " + counter[0]);

Mutable Wrapper Objects

Use or create a simple wrapper class that holds a mutable field:

class IntWrapper {
    int value;
}

IntWrapper sum = new IntWrapper(); // Reference stays the same
sum.value = 0;

list.forEach(item -> {
    sum.value += item; // Modifying field, not the reference
});

System.out.println("Sum: " + sum.value);

When to Use These Techniques

These workarounds should be rare. Most functional-style code avoids mutation entirely. However, they're useful when integrating with APIs that don't provide alternatives or when performance is critical in specific scenarios.

Key Takeaway: You can work around the effectively final restriction by using single-element arrays or mutable wrapper objects—the reference stays constant while the internal contents change, satisfying both the compiler and your need to update values.