Java parameterization

I understand a little about generics and the need to parameterize when you use actual instances of Array and such. I wasn’t familiar with the need to parameterize Class or ArrayAdapter. I’m working with Java 6 here so I may be in uncharted (or at least unsupported) waters.

The fun started when I decided to subclass ArrayAdapter so that I could hand it an array of classes (Activity classes, in fact – then when one is selected, just startActivity on it) and have the adapter construct a ListView from them (all I have to do is override getView).

    private class ClassesAdapter extends ArrayAdapter {

Whoops! Evidently (Eclipse informs me) ArrayAdapter is a raw type and needs to be parameterized. I didn’t even know it would be necessary to deal with that in a subclass. Obviously I need to go back and read about generics again. But wait, I know what kind of array I’m handing in, so I can actually parameterize this extension (and the constructor too). And I even know what kind of Class I’ll be handing in – have to parameterize Class too.

  private class ClassesAdapter extends ArrayAdapter<Class<Activity>> {
      public ClassesAdapter(Context context, int viewId, Class<Activity>[] objects) {

Fine. Now the fun continues when I actually try to create the array of Class objects.

        Class[] classes = new Class[] {Drawables.class};

Nope! Complaints about raw type, unchecked conversion.

        Class<Activity>[] classes = new Class<Activity>[] {Drawables.class};
        Class[] classes = new Class<Activity>[] {Drawables.class};

No – these add an actual error – type mismatch!

        Class<Activity>[] classes = new Class[] {Drawables.class};

This still complains, but only about unchecked conversion. OK, probably I don’t really understand what I’m doing parameterizing a Class, but it does at least work, and produces the fewest warnings. I’ll have to hit up Google at some point.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: