Search code examples
javaandroidlistadapter

is both codes have the same meaning?


currently i'm studying the setListAdapter, and have come across 2 snippets of code below.

Snippet 1:

ArrayAdapter<String> adapter =
    new ArrayAdapter<String>(this, R.layout.layout_nm, R.id.layout_idnm, items);
setListAdapter(adapter);

Snippet 2:

setListAdapter(new ArrayAdapter<String>(this, R.layout.layout_nm, R.id.layout_idnm, items););   

my question is:

  1. do both snippets have the same meaning?
  2. does the second snippet define ArrayAdapter?

Solution

  • 1. There is an extra ";" in the 2nd option, so remove it...

    Before:

    setListAdapter(new ArrayAdapter<String>(this, R.layout.layout_nm, R.id.layout_idnm, items););
    

    After:

    setListAdapter(new ArrayAdapter<String>(this, R.layout.layout_nm, R.id.layout_idnm, items));
    

    2. If you are using the 2nd approach you are NOT creating a local variable, this will create a problem when you will need to refer this ArrayList object again in the code.

    For example you will need this local variable if you want to do something like notifyDataSetChanged()