How can I cast a ListModel to a DefaultListModel??! I perform the following and I get this error message,
DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();
C:\Documents and Settings\...\myfile.java:728: warning: [rawtypes] found raw type: DefaultListModel
DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();
missing type arguments for generic class DefaultListModel<E>
where E is a type-variable:
E extends Object declared in class DefaultListModel
I tried the following,
DefaultListModel<E> portalListModel = (DefaultListModel) portalList.getModel();
I have a feeling tha this is a stupid question but I’m totally confued with this new generic thing! Please help me out!
The way that Java’s Collections work is that you can use Collection-type objects to store a whole bunch of Objects. Prior to the introduction of Generics, you could store any object in a Collection, and then you had to perform a cast when you wanted to get those Objects out of your collection.
That’s perfectly acceptable code. If you wanted to iterate over the objects, you could do it like so:
With Java 1.5, Generics provides compile-time type checking upon insertion into the list. So now, if you declare
myListas aList<String>, the first block of code above will fail at compile time when you attempt to add an object of typeMyValueClassto the List.In Java 1.7,
DefaultListModelis genericized. So when you callportalList.getModel(), you’re going to get back aDefaultListModelthat contains a certain type of object (which is what the<E>is; it’s a placeholder for the actual object type.) In the aboveList<String>example,Stringis the substitution forE.So if your
portalListobject’smodelmember is aDefaultListModelthat contains a bunch ofMyValueClassobjects, then your declaration should look like:See the DefaultListModel API doc.