문제

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;
            }
        });
    }
도움이 되었습니까?

해결책 2

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.

다른 팁

Eclipse isn't forcing anything. Java requires that local variables be declared final if they're used in anonymous inner classes. These classes make copies of any local variable used, and if the variable is not final, the original and the copy may be referring to a different value.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top