Search code examples
javaconstructorfinal

Why does eclipse force me to use a final?


I have a constructor with size as a parameter. Eclipse forces me to declare Integer size as final. Why ?

   public LRUCache(final Integer size) {
        lhm = Collections.synchronizedMap(new LinkedHashMap<String, Integer>() {
            @Override
            public boolean removeEldestEntry(Map.Entry eldest) {
                return size() > size;
            }
        });
    }

Solution

  • size is a reference to an Integer object. When you do

    size() > size
    

    you are dereferencing size to get its int value. Because removeEldestEntry happens at in a different context, at a different time, there needs to be some guarantee that the reference you are using is the same you are declaring. Therefore you need final, ie. so the reference cannot change.

    In the Java Language Specification

    Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

    and

    Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.

    and

    V is definitely assigned before an anonymous class declaration (§15.9.5) that is declared within the scope of V iff V is definitely assigned after the class instance creation expression that declares the anonymous class.