Why the list must be declare by final

102 views Asked by At
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?

2

There are 2 answers

0
morgano On BEST ANSWER

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.

0
Andy On

The scope of 'tempList' is within the method. When the method finishes, 'tempList' will eventually be lost. However, the anonymous class you wrote might still be on the heap and could be referenced later. Making it final will make sure that the anonymous class will still behave as expected.