2
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?

Frank Yeung
  • 315
  • 1
  • 3
  • 11
  • Well, simply because the language requires it. I think it's because the (original) language writers made an error -- final here doesn't really do much, other than remind you of the reference by the inner class. But you have to use final or the inner class can't use the reference. – markspace Oct 24 '14 at 03:11
  • As of Java 8, it doesn't actually have to be declared final, though it must be "effectively" final. – Louis Wasserman Oct 24 '14 at 03:26
  • http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html – etherous Oct 24 '14 at 03:29
  • My opinion is 'no need final'. – Sai Ye Yan Naing Aye Oct 24 '14 at 08:29

2 Answers2

2

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.

Andy
  • 1,023
  • 1
  • 9
  • 17
1

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.

morgano
  • 17,210
  • 10
  • 45
  • 56