1

I"ve read enter link description here

and see that a anonymous class gets copies of the execution context of the outer class variables. No where can i find if the anonymous class gets a shallow copy or deep copy of the final variables. I tried doing a test using Using some android code but it can be any java platform. I tried to test this:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = (TextView)findViewById(R.id.tv);

    final List<String> jason = new ArrayList<>();
    jason.add("my first string");
    tv.setOnClickListener(new View.OnClickListener(){


        @Override
        public void onClick(View v) {
            Log.v("mytag",jason.get(0));
        }
    });
    jason.clear();
    jason.add("my second string");

}

}

and the output in the logs when i click the text is "my second string".

so it seems that when i alter the list from the outer class it indeed affected the anonymous class. So can i assume it always gets a shallow copy then ?

Community
  • 1
  • 1
j2emanue
  • 60,549
  • 65
  • 286
  • 456

1 Answers1

4

From the Java tutorial:

... a local class has access to local variables.

(where "local class" also applies to "anonymous class").

Note that it says variables, not objects. So there is no deep copying going on.


You can verify this experimentally with the following code:

final ArrayList<Integer> list = new ArrayList<>();
list.add(5);

new Runnable() { public void run() { list.add(6); } }.run();

System.out.println(list);   // [5, 6] (would be [5] if had been deep-copied)

(Live demo)

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680