3

As explained in what-is-a-raw-type-and-why-shouldnt-we-use-it, using raw classes is evil.

Now, the Spinner .getSelectedItem() returns an object where it could return the correct class if it were initialized with Spinner<CorrectClass>.

Why is this so?

Community
  • 1
  • 1
serv-inc
  • 35,772
  • 9
  • 166
  • 188

1 Answers1

2

getSelectedItem() is a method of AdapterView which return Adapter#getItem(). So the question is "Why the interface Adapter is not generic ?".

The answer is simply because an Android widget AdapterView can be used to store objects of different type. The purpose of the Adapter is to provide a consistent view of these objects.

If you add a generic parameter to the interface Adapter (and AdapterView, and Spinner), you are fixing the type of the underlying data collection wich goes against the whole adapter thing.

The idea is that the adapter view doesn't need to be aware of the underlying data behind the adapter, thus it should'nt need to constrain its data type.

You can however specialize the Adapter interface with a specific type (or a generic argment) in your own SpinnerAdapter implementation and then access the data via the Adapter and not the AdapterView :

yourAdapter.getItem(spinner.getSelectedItemPosition()).
zakinster
  • 10,508
  • 1
  • 41
  • 52
  • Do you have an idea why `ArrayAdapter` has generics? – serv-inc Jul 31 '15 at 10:15
  • 1
    @user1587329 it's a choice of conception, an `ArrayAdapter` car only handle one kind of data. It's way easier to put that kind of constraint in a particular implementation (with a particular use case in mind) rather than on the whole general interface. – zakinster Jul 31 '15 at 10:23
  • Still, the `Spinner` could just as well be typed with the option to use a raw type, n'est-ce pas? – serv-inc Jul 31 '15 at 10:28
  • The `Spinner` is a specialization of an `AdapterView`. The idea is that the adapter view doesn't need to be aware of the underlying type behind the adapter, thus it should'nt need to constrain the data type of the adapter. If you want to specialize the adapter type, do it in your own `SpinnerAdapter` implementation and don't call `spinner.getSelectedItem()` but `yourAdapter.getItem(spinner.getSelectedItemPosition())`. – zakinster Jul 31 '15 at 12:42