The final modification variable conflicts with the anonymous inner class call

For ordinary variables, it is immutable, but for reference types, the address in the heap memory is immutable, but the value of the reference type can be changed; in
special cases (it can be solved by other means, here is just an example ): A local variable is called in an anonymous inner class, then this variable needs to be final, but it must be initialized;

        int score = 0;//这里报错,因为score在内部类中调用,必须声明称final而且必须初始化
        button.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                score++;
            }
        });

After modification, it is as follows: Solved by reference type, the reference address remains unchanged, but the pointed content remains unchanged

        final int[] score = {
    
    0};
        button.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                score[0]++;
            }
        });

Only this record problem, the scene is of little significance

Guess you like

Origin blog.csdn.net/nongminkouhao/article/details/114981216
Recommended