Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Constructor is ambiguous when I pass Null, but not when I pass a variable assigned to Null [duplicate]

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?

like image 646
Solace Avatar asked Dec 17 '14 12:12

Solace


3 Answers

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.

like image 127
Petter Avatar answered Oct 15 '22 16:10

Petter


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.

like image 22
Mou Avatar answered Oct 15 '22 17:10

Mou


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.

like image 2
Aaryn Tonita Avatar answered Oct 15 '22 17:10

Aaryn Tonita