4

First of all, I come from iOS environment, so this is why this question might be obvious.

I know Android has Garbage Collector, but objects still reference (retain) other objects, and my understanding is the GC will only remove an object if it has no references (probably I'm wrong in this point). Looking at this code:

private void addDefaultTextWatcher(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                value = s.toString();
                if (getOnValidate() != null) {
                    getOnValidate().validate(editText, s.toString());
                }
            }
        });
    }

editTexthas a reference the TextWatcher anonymous class, and that class has a reference to editText as well. Is Garbage collector going to take care of this for me? If no... what is the suggested approach?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
LocoMike
  • 5,626
  • 5
  • 30
  • 43
  • 1
    Not 'if it has references', its 'if it cannot be reached'. The garbage collector isn't looking for things it *can* collect, its looking for things it *can't* collect and collecting the rest [slight oversimplification] – Richard Tingle Jul 16 '13 at 19:18

1 Answers1

6

Java Garbage Collector is smart enough to recognize cycle references. You should do nothing.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158