Reputation: 2792
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!
Upvotes: 2
Views: 3971
Reputation: 8100
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.
List myList = new ArrayList();
myList.add("string");
myList.add(new MyValueClass(42, "identifying string"));
That's perfectly acceptable code. If you wanted to iterate over the objects, you could do it like so:
Iterator it = myList.iterator();
while (it.hasNext()) {
String str = (String) it.next(); // NOTE: This will work the first time, but throw a ClassCastException when it gets to the second item.
}
With Java 1.5, Generics provides compile-time type checking upon insertion into the list. So now, if you declare myList
as a List<String>
, the first block of code above will fail at compile time when you attempt to add an object of type MyValueClass
to the List.
In Java 1.7, DefaultListModel
is genericized. So when you call portalList.getModel()
, you're going to get back a DefaultListModel
that contains a certain type of object (which is what the <E>
is; it's a placeholder for the actual object type.) In the above List<String>
example, String
is the substitution for E
.
So if your portalList
object's model
member is a DefaultListModel
that contains a bunch of MyValueClass
objects, then your declaration should look like:
DefaultListModel<MyValueClass> portalListModel = portalList.getModel();
See the DefaultListModel API doc.
Upvotes: 5