Android: constructor is ambiguous when I skip Null, but not when pass a variable assigned by Null

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 an error that the constructor call is ambiguous.

I understand that when null is passed, it is not clear which of the ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) and ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects) we call.

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 an error, although I am still missing null , right?

Why is this happening?

+5
source share
3 answers

This is because in the second case, arrayList is a variable of type ArrayList that is null. In the first case, there is no information about the type of the parameter, so the compiler does not know which method should be called. You can do the first case by using (List) null as an argument.

+9
source

When you set zero like this:

 ArrayAdapter(context, resource, textViewResourceId, null); 

You set a null pointer (a pointer to nothing place), and this null can be any object.

On the other hand, when you do this:

 ArrayList arrayList = null; ArrayAdapter arrayListAdapter = new ArrayAdapter(getActivity(), R.layout.fragment_result_titles, R.layout.row_listview, arrayList); 

An pointer of type ArrayList is created in memory (indicating the absence of an object, but with a type ). Java can only assign an object to a variable of the same type (or inherited type). Thus, this is not yet ambiguous, and the compiler can know which method should be used.

+2
source

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 supply the type information needed by Java to solve the ambiguity of which constructor to use.

+2
source

Source: https://habr.com/ru/post/1209347/


All Articles