I wrote the following statement to create an ArrayAdapter<String>
,
ArrayAdapter<String> arrayListAdapter = new ArrayAdapter<String>(getActivity(), R.layout.fragment_result_titles, R.layout.row_listview, arrayList);
But I got the error that the constructor call is ambiguous.
I understand that when null is passed, it is not clear which among ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
and ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)
are we calling.
But then I tried this:
ArrayList arrayList = null;
ArrayAdapter<String> arrayListAdapter = new ArrayAdapter<String>(getActivity(), R.layout.fragment_result_titles, R.layout.row_listview, arrayList);
This does not give the error, although I am still passing null
, isn't it?
Why is this happening?
This happens because in the second case, arrayList is a variable of type ArrayList which happens to be null. In the first case, there is no type information about the parameter so the compiler doesn't know which method should be invoked. You can make the first case work by using (List) null
as the argument.
When you set null like this:
ArrayAdapter(context, resource, textViewResourceId, null);
You are setting a null pointer (pointer to nothing place) and this null can be any object.
By other hand, when you do this:
ArrayList arrayList = null;
ArrayAdapter arrayListAdapter = new ArrayAdapter(getActivity(), R.layout.fragment_result_titles, R.layout.row_listview, arrayList);
You are creating an ArrayList type pointer in memory (pointing to no object, but with type). Java only can assign a object to a variable of the same type (or inherited type). So, this are not ambiguous yet and compiler can know which method must be use.
To add to Petter's answer, the following will also work:
new ArrayAdapter<String>(getActivity(), R.layout.fragment_result_titles, R.layout.row_listview, (ArrayList)null);
precisely because you are supplying the type information that Java needs in order to solve the ambiguity of which constructor to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With