If you declare the extended for statement and for Each statement normally, it will be as follows.
Since it is not declared final
, it can be reassigned (normal for
statements are skipped because reassignment is essential in principle).
List<Integer> intList = Arrays.asList(1, 2, 3, 4);
for(int i : intList) {
i = 0; //Can be rewritten
}
intList.forEach(it -> {
it = 0; //Can be rewritten
});
In this article, we will rewrite these contents into a non-reassignable form.
You can make it ʻimmutable by declaring it with
final`.
for(final int i : intList) {
i = 0; //Since it is declared final, it cannot be reassigned and a compile error occurs.
}
You can make the argument final
by specifying the type in parentheses as shown below.
intList.forEach((final int it) ->
it = 0; //Since it is declared final, it cannot be reassigned and a compile error occurs.
);
For the time being, the argument can be final
even when implementing it as an anonymous class.
Consumer<Integer> finalConsumer = new Consumer<Integer>() {
@Override
public void accept(final Integer it) {
it = 0; //Since it is declared final, it cannot be reassigned and a compile error occurs.
}
};
When this article was first published, the title and content was "** Indexes can be immutable only for extended for statements, extended for statements, and forEach statements **", but @ saka1029 pointed out. As you can see, this was an error, so I completely rewrote both the title and content.
Thank you for pointing out @ saka1029.
Recommended Posts