Search code examples
javatrove4j

Why the list must be declare by final


TIntArrayList list = new TIntArrayList();
final TIntArrayList tempList = new TIntArrayList();
list.add(10086);
list.add(12345);
list.add(1989);
list.forEach(new TIntProcedure() {
    @Override
    public boolean execute(int i) {
        if (i > 10086) {
            tempList.add(i);
        }
        return true;
    }
});

I use intellij, and it prompts me to declare tempList by final,why the tempList has to be declared by final?


Solution

  • It's because of the way the virtual machine works.

    First, to understand this, you need to know what the internal stack and stack frames are (inside the virtual machine)

    Local variables (both primitives and references) are stored in the method's stack frame and are not accessible by other methods.

    In your case, the local variable tempList is not accessible in the method boolean execute(int i) because it "belongs" to the enclosing method (it "lives" in the local stack frame).

    But, for it to make it accessible you declare the variable final, this way it is internally put "outside" of the method, like if it was a private instance variable, so that it can be accessed by execute() and other methods.