3

While making an android app I encountered and issue regarding accessing a non final variable from an inner class. used This as a reference.

I wanted to ask what is the "proper" and efficient way to do this? my two solutions are below:

for (Button b : buttonArray) {
      final Button bb = b;
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text.append(bb.getText().toString());
                //Appending "1".."0" to a textView
            }
        });
    }

OR

 for (final Button b : buttonArray) {...}

//please feel free to suggest a better way. I will try to use lambda expressions to beautify the code later

Ali Pardhan
  • 194
  • 1
  • 14

2 Answers2

1

There's no performance difference between this:

for (Button b : buttonArray) {
      final Button bb = b;
     ...
     ...

and this:

for (final Button b : buttonArray) {...}

However, I'd recommend the second approach because I see it as redundancy to create a new variable that points to the same object in memory as the iteration variable which you then operate upon.

Also, using lambdas you can make your code cleaner with:

for (Button b : buttonArray) {
     b.addActionListener(v -> {
         text.append(b.getText().toString());
     });
}

note that in this case, we don't even need to declare the iteration variable as final as it already satisfies the effectively final rule.

as an aside, you could convert the entire code with the use of streams as such:

Arrays.stream(buttonArray).forEach(button -> {
      button.addActionListener(v -> {
           text.append(button.getText().toString());
      });
});
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

I think you are not asking any question about how the 'final' keyword works instead how the foreach loop works. As long as foreach loop is working by taking one instance at a time both of your declaration should be as efficient.

ruben
  • 1,745
  • 5
  • 25
  • 47
  • See the first line of the question : "I encountered and issue regarding accessing a non final variable from an inner class". So it's about accessing a final/non final variable from inner class. But in the end it became a foreach loop related question. – ruben Dec 11 '17 at 12:10