Search code examples
javaandroidlistandroid-recyclerviewandroid-arrayadapter

In android This code is working Can anyone tell me why and how?


In Android I was practicing recycling view and I notice when i am contverting an String type array into Integer type list it is working fine as well as when i am putting string type list into Interger type ArrayAdapter it is working fine.

 String[] words = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};

 List<Integer> listOfWords = new ArrayList(Arrays.asList(words));

ArrayAdapter<Integer> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,listOfWords);

ListView listView = (ListView) findViewById(R.id.list);

listView.setAdapter(adapter);

Solution

  • It's actually about Java rather than Android. Java Collections (e.g. ArrayList) use collections of objects under the hood and when you define an ArrayList<Integer> and an ArrayList<String> there actually no difference between them. They both hold a Object[] inside. So actually the only difference they have, is how the compiler treat them and if we use generic functions like get it will lead to a ClassCastException because you can find a unchecked cast inside their implementation.

    ArrayAdapter is also defined in the same way and actually Lists and ArrayAdapter are not checking any types. In other words you've fooled the IDE, lint and compiler and because there is not type checking here, it can work without any problem (I'm not sure but I think inside ArrayAdapter there is a code which calls toString for each element or checks if it's a string or not using instanceof). In addition, even if you use List<Object> it is still able to function without any problem.