Noob question: how to create generic object holding multiple types

Hi,

I have been working through the sun tutorials, and I am having some difficulty getting the hang of generics...

The tutorial's excercise suggests the following class to function as a library for books, videos and newspapers:

--

import java.util.List;

import java.util.ArrayList;

public class Library<E extends Media> {

private List<E> resources = new ArrayList<E>();

public void addMedia(E x) {

resources.add(x);

}

public E retrieveLast() {

int size = resources.size();

if (size > 0) {

return resources.get(size - 1);

}

return null;

}

}

--

If I want to create an instance of this class that will allow books, videos or newspapers to be added, how should the class be instaniated?

I have tried:

Library<? extends Media> testLibrary = new Library<? extends Media>();

The tutorial isn't very clear on how to go about doing this. Any help is appreciated!

[1035 byte] By [sourceLakeJakea] at [2007-11-27 4:49:45]
# 1
I would think your Books, NewsPapers, and Videos would all have to implement some interface MyMedia which in turn implemented Media. Then your call would be:Library<MyMedia> _lib = new Library<MyMedia>();
DejasPerPera at 2007-7-12 10:02:53 > top of Java-index,Core,Core APIs...
# 2

The tutorial defines the following interfaces:

interface Media {

}

interface Book extends Media {

}

interface Video extends Media {

}

interface Newspaper extends Media {

}

So, should the call be:

Library<Media> lib = new Library<Media>();

sourceLakeJakea at 2007-7-12 10:02:53 > top of Java-index,Core,Core APIs...
# 3
> So, should the call be:> > Library<Media> lib = new Library<Media>();Yes. That appears to be what you want.
dubwaia at 2007-7-12 10:02:53 > top of Java-index,Core,Core APIs...
# 4

Yes, new Library<Media> will do what you want.

As you have no doubt discovered, you cannot instatiate a <? extends ...> class; the type has to be something concrete. So you need to choose the 'greatest common demoninator' ie the first thing you hit that they all implement.

Because the library is now typed by the super-interface, it will still accept all the subclasses of that interface just like a normal (untyped) method would. However, because the type of the library is Media, not something more specific, the retrieveLast method will have a return type of Media, so you cannot (without casting) retrieve the implementing class.

Hope that clears it up some.

matchamia at 2007-7-12 10:02:53 > top of Java-index,Core,Core APIs...